keras结合了预训练模型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了keras结合了预训练模型相关的知识,希望对你有一定的参考价值。
我训练了一个模型并希望使用功能性api将其与另一个keras模型相结合(后端是tensorflow版本1.4)
我的第一个模型看起来像这样:
import tensorflow.contrib.keras.api.keras as keras
model = keras.models.Sequential()
input = Input(shape=(200,))
dnn = Dense(400, activation="relu")(input)
dnn = Dense(400, activation="relu")(dnn)
output = Dense(5, activation="softmax")(dnn)
model = keras.models.Model(inputs=input, outputs=output)
在我训练这个模型后,我使用keras model.save()方法保存它。我也可以加载模型并重新训练它没有问题。
现在我想使用此模型的输出作为第二个模型的附加输入:
# load first model
old_model = keras.models.load_model(path_to_old_model)
input_1 = Input(shape=(200,))
input_2 = Input(shape=(200,))
output_old_model = old_model(input_2)
merge_layer = concatenate([input_1, output_old_model])
dnn_layer = Dense(200, activation="relu")(merge_layer)
dnn_layer = Dense(200, activation="relu")(dnn_layer)
output = Dense(10, activation="sigmoid")(dnn_layer)
new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
new_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
new_model.fit(inputs=[x1,x2], labels=labels, epochs=50, batch_size=32)
当我尝试这个时,我收到以下错误消息:
FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_1/kernel
[[Node: dense_1/kernel/read = Identity[T=DT_FLOAT, _class=["loc:@dense_1/kernel"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](dense_1/kernel)]]
[[Node: model_1_1/dense_3/BiasAdd/_79 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_68_model_1_1/dense_3/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
答案
我会按照以下步骤执行此操作:
- 定义使用相同架构构建清洁模型的功能:
def build_base(): input = Input(shape=(200,)) dnn = Dense(400, activation="relu")(input) dnn = Dense(400, activation="relu")(dnn) output = Dense(5, activation="softmax")(dnn) model = keras.models.Model(inputs=input, outputs=output) return input, output, model
- 构建同一模型的两个副本:
input_1, output_1, model_1 = build_base() input_2, output_2, model_2 = build_base()
- 在两个模型中设置权重:
model_1.set_weights(old_model.get_weights()) model_2.set_weights(old_model.get_weights())
- 现在做其余的事情:
merge_layer = concatenate([input_1, output_2]) dnn_layer = Dense(200, activation="relu")(merge_layer) dnn_layer = Dense(200, activation="relu")(dnn_layer) output = Dense(10, activation="sigmoid")(dnn_layer) new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
以上是关于keras结合了预训练模型的主要内容,如果未能解决你的问题,请参考以下文章