python - 在 TF 估计器中使用 Keras 模型

标签 python tensorflow keras

我想使用 tf.keras.application 中包含的一种预建 keras 模型(vgg、inception、resnet 等)进行特征提取,以节省我一些训练时间。

在估算器模型函数中执行此操作的正确方法是什么?

这是我目前拥有的。

import tensorflow as tf

def model_fn(features, labels, mode):

    # Import the pretrained model
    base_model = tf.keras.applications.InceptionV3(
            weights='imagenet', 
            include_top=False,
            input_shape=(200,200,3)
    )

    # get the output features from InceptionV3
    resnet_features = base_model.predict(features['x'])

    # flatten and feed into dense layers
    pool2_flat = tf.layers.flatten(resnet_features)

    dense1 = tf.layers.dense(inputs=pool2_flat, units=5120, activation=tf.nn.relu)

    # ... Add in N number of dense layers depending on my application

    logits = tf.layers.dense(inputs=denseN, units=5)

    # Calculate Loss
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=5)

    loss = tf.losses.softmax_cross_entropy(
    onehot_labels=onehot_labels, logits=logits)

    optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step()
    )

    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

if __name__ == "__main__":

    # import Xtrain and Ytrain

    classifier = tf.estimator.Estimator(
        model_fn=model_fn, model_dir="/tmp/conv_model")

    train_input_fn = tf.estimator.inputs.numpy_input_fn(
        x={'x': Xtrain},
        y=Ytrain,
        batch_size=100,
        num_epochs=None,
        shuffle=True)

    classifier.train(
        input_fn=train_input_fn,
        steps=100)

但是,这段代码会抛出错误:

TypeError: unsupported operand type(s) for /: 'Dimension' and 'float'

resnet_features = base_model.predict(features['x']) 行

我认为这是因为 keras 模型需要一个 numpy 数组,但估算器传入的是一个 tf.Tensor。

那么,在估算器中使用 keras 模型的正确方法是什么。而且,如果您不打算这样做,那么在 TF 中利用预训练模型进行迁移学习的最简单方法是什么?

最佳答案

我不知道有任何可用的方法允许您从预训练的 keras 模型创建自定义 model_fn。一种更简单的方法是使用 tf.keras.estimator.model_to_estimator()

model = tf.keras.applications.ResNet50(
    input_shape=(224, 224, 3),
    include_top=False,
    pooling='avg',
    weights='imagenet')
logits =  tf.keras.layers.Dense(10, 'softmax')(model.layers[-1].output)
model = tf.keras.models.Model(model.inputs, logits)
model.compile('adam', 'categorical_crossentropy', ['accuracy'])

# Convert Keras Model to tf.Estimator
estimator = tf.keras.estimator.model_to_estimator(keras_model=model)
estimator.train(input_fn=....)

但是,如果您想创建自定义 model_fn 以添加更多操作(例如摘要操作),您可以编写如下:

import tensorflow as tf

_INIT_WEIGHT = True

def model_fn(features, labels, mode, params):
  global _INIT_WEIGHT

  # This is important, it allows keras model to update weights
  tf.keras.backend.set_learning_phase(mode == tf.estimator.ModeKeys.TRAIN)

  model = tf.keras.applications.MobileNet(
      input_tensor=features,
      include_top=False,
      pooling='avg',
      weights='imagenet' if _INIT_WEIGHT else None)

  # Only init weights on first run
  if _INIT_WEIGHT:
    _INIT_WEIGHT = False

  feature_map = model(features)
  logits = tf.keras.layers.Dense(units=params['num_classes'])(feature_map)

  # loss
  loss = tf.losses.softmax_cross_entropy(labels=labels, logits=logits)
  ...

关于python - 在 TF 估计器中使用 Keras 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48295788/

相关文章:

python - 是否可以重新训练以前保存的 keras 模型?

python - 批量归一化导致训练和推理损失之间存在巨大差异

python - 有没有办法加速 tf.keras 中的嵌入层?

python - Keras train_on_batch() 与 fit() 相比不训练模型

python - 为了获得范围,下面的语句有什么区别?

Python 和 SQLite : Can't execute query due to a syntax error

tensorflow - Keras 使用经过训练的 InceptionV3 模型 + CIFAR10 出现有关 Batch Size 的错误

machine-learning - Keras,稀疏矩阵问题

python - 使用 CNN 对长格式音频进行特征提取以识别关键字

Python打印函数不按顺序打印