我不知道有任何可用的方法可以让您从预先训练的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.Estimatorestimator = tf.keras.estimator.model_to_estimator(keras_model=model)estimator.train(input_fn=....)
但是,如果您想创建自定义model_fn来添加更多 *** 作(例如,摘要 *** 作),则可以编写如下:
import tensorflow as tf_INIT_WEIGHT = Truedef 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) ...
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)