我正在尝试开发一个用于简单面部验证的暹罗网络(以及第二阶段的识别)。我有一个网络,我设法训练,但我有点困惑,如何保存和恢复模型+使用训练模型进行预测。希望该域名中有经验的人可以帮助取得进展。
以下是我创建暹罗网络的方式,首先是......
model = ResNet50(weights='imagenet') # get the original ResNet50 model
model.layers.pop() # Remove the last layer
for layer in model.layers:
layer.trainable = False # do not train any of original layers
x = model.get_layer('flatten_1').output
model_out = Dense(128, activation='relu', name='model_out')(x)
model_out = Lambda(lambda x: K.l2_normalize(x,axis=-1))(model_out)
new_model = Model(inputs=model.input, outputs=model_out)
# At this point, a new layer (with 128 units) added and normalization applied.
# Now create siamese network on top of this
anchor_in = Input(shape=(224, 224, 3))
positive_in = Input(shape=(224, 224, 3))
negative_in = Input(shape=(224, 224, 3))
anchor_out = new_model(anchor_in)
positive_out = new_model(positive_in)
negative_out = new_model(negative_in)
merged_vector = concatenate([anchor_out, positive_out, negative_out], axis=-1)
# Define the trainable model
siamese_model = Model(inputs=[anchor_in, positive_in, negative_in],
outputs=merged_vector)
siamese_model.compile(optimizer=Adam(lr=.0001),
loss=triplet_loss,
metrics=[dist_between_anchor_positive,
dist_between_anchor_negative])
我训练了siamese_model。当我训练它时,如果我正确地解释结果,它不是真正训练基础模型,它只是训练新的暹罗网络(基本上,只是最后一层被训练)。
但是这个模型有3个输入流。在训练之后,我需要以某种方式保存这个模型,这样它只需要1或2个输入,这样我就可以通过计算2个给定图像之间的距离来执行预测。如何保存此模型并立即重复使用?
提前谢谢!
如果您想知道,这里是暹罗模型的摘要。
siamese_model.summary()
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_2 (InputLayer) (None, 224, 224, 3) 0
__________________________________________________________________________________________________
input_3 (InputLayer) (None, 224, 224, 3) 0
__________________________________________________________________________________________________
input_4 (InputLayer) (None, 224, 224, 3) 0
__________________________________________________________________________________________________
model_1 (Model) (None, 128) 23849984 input_2[0][0]
input_3[0][0]
input_4[0][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate) (None, 384) 0 model_1[1][0]
model_1[2][0]
model_1[3][0]
==================================================================================================
Total params: 23,849,984
Trainable params: 262,272
Non-trainable params: 23,587,712
__________________________________________________________________________________________________
答案 0 :(得分:1)
您可以使用以下代码保存模型 siamese_model.save_weights(MODEL_WEIGHTS_FILE)
然后要加载模型,您需要使用 siamese_model.load_weights(MODEL_WEIGHTS_FILE)
谢谢