我在Resnet50中使用转移学习。我根据Keras提供的预训练模型(“图像网络”)创建了一个新模型。
训练完新模型后,我将其保存如下:
# Save the Siamese Network architecture
siamese_model_json = siamese_network.to_json()
with open("saved_model/siamese_network_arch.json", "w") as json_file:
json_file.write(siamese_model_json)
# save the Siamese Network model weights
siamese_network.save_weights('saved_model/siamese_model_weights.h5')
然后,我按照以下说明重新加载它:
json_file = open('saved_model/siamese_network_arch.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
siamese_network = model_from_json(loaded_model_json)
# load weights into new model
siamese_network.load_weights('saved_model/siamese_model_weights.h5')
然后我检查权重是否看起来合理(如下所示)(从1层):
print("bn3d_branch2c:\n",
siamese_network.get_layer('model_1').get_layer('bn3d_branch2c').get_weights())
如果仅将我的网络训练1个纪元,那我会看到合理的值。
但是,如果我训练模型18个纪元(因为我的计算机速度很慢,则需要5-6个小时),我只会看到NaN值,如下所示:
bn3d_branch2c:
[array([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
...
这里的窍门是什么?
附录1:
这是我创建模型的方式。
在这里,我有一个Triplet_loss函数,稍后我会用到。
def triplet_loss(inputs, dist='euclidean', margin='maxplus'):
anchor, positive, negative = inputs
positive_distance = K.square(anchor - positive)
negative_distance = K.square(anchor - negative)
if dist == 'euclidean':
positive_distance = K.sqrt(K.sum(positive_distance, axis=-1, keepdims=True))
negative_distance = K.sqrt(K.sum(negative_distance, axis=-1, keepdims=True))
elif dist == 'sqeuclidean':
positive_distance = K.sum(positive_distance, axis=-1, keepdims=True)
negative_distance = K.sum(negative_distance, axis=-1, keepdims=True)
loss = positive_distance - negative_distance
if margin == 'maxplus':
loss = K.maximum(0.0, 2 + loss)
elif margin == 'softplus':
loss = K.log(1 + K.exp(loss))
returned_loss = K.mean(loss)
return returned_loss
这是我从头到尾构造模型的方式。我给出了完整的代码以给出确切的图片。
model = ResNet50(weights='imagenet')
# Remove the last layer (Needed to later be able to create the Siamese Network model)
model.layers.pop()
# First freeze all layers of ResNet50. Transfer Learning to be applied.
for layer in model.layers:
layer.trainable = False
# All Batch Normalization layers still need to be trainable so that the "mean"
# and "standard deviation (std)" params can be updated with the new training data
model.get_layer('bn_conv1').trainable = True
model.get_layer('bn2a_branch2a').trainable = True
model.get_layer('bn2a_branch2b').trainable = True
model.get_layer('bn2a_branch2c').trainable = True
model.get_layer('bn2a_branch1').trainable = True
model.get_layer('bn2b_branch2a').trainable = True
model.get_layer('bn2b_branch2b').trainable = True
model.get_layer('bn2b_branch2c').trainable = True
model.get_layer('bn2c_branch2a').trainable = True
model.get_layer('bn2c_branch2b').trainable = True
model.get_layer('bn2c_branch2c').trainable = True
model.get_layer('bn3a_branch2a').trainable = True
model.get_layer('bn3a_branch2b').trainable = True
model.get_layer('bn3a_branch2c').trainable = True
model.get_layer('bn3a_branch1').trainable = True
model.get_layer('bn3b_branch2a').trainable = True
model.get_layer('bn3b_branch2b').trainable = True
model.get_layer('bn3b_branch2c').trainable = True
model.get_layer('bn3c_branch2a').trainable = True
model.get_layer('bn3c_branch2b').trainable = True
model.get_layer('bn3c_branch2c').trainable = True
model.get_layer('bn3d_branch2a').trainable = True
model.get_layer('bn3d_branch2b').trainable = True
model.get_layer('bn3d_branch2c').trainable = True
model.get_layer('bn4a_branch2a').trainable = True
model.get_layer('bn4a_branch2b').trainable = True
model.get_layer('bn4a_branch2c').trainable = True
model.get_layer('bn4a_branch1').trainable = True
model.get_layer('bn4b_branch2a').trainable = True
model.get_layer('bn4b_branch2b').trainable = True
model.get_layer('bn4b_branch2c').trainable = True
model.get_layer('bn4c_branch2a').trainable = True
model.get_layer('bn4c_branch2b').trainable = True
model.get_layer('bn4c_branch2c').trainable = True
model.get_layer('bn4d_branch2a').trainable = True
model.get_layer('bn4d_branch2b').trainable = True
model.get_layer('bn4d_branch2c').trainable = True
model.get_layer('bn4e_branch2a').trainable = True
model.get_layer('bn4e_branch2b').trainable = True
model.get_layer('bn4e_branch2c').trainable = True
model.get_layer('bn4f_branch2a').trainable = True
model.get_layer('bn4f_branch2b').trainable = True
model.get_layer('bn4f_branch2c').trainable = True
model.get_layer('bn5a_branch2a').trainable = True
model.get_layer('bn5a_branch2b').trainable = True
model.get_layer('bn5a_branch2c').trainable = True
model.get_layer('bn5a_branch1').trainable = True
model.get_layer('bn5b_branch2a').trainable = True
model.get_layer('bn5b_branch2b').trainable = True
model.get_layer('bn5b_branch2c').trainable = True
model.get_layer('bn5c_branch2a').trainable = True
model.get_layer('bn5c_branch2b').trainable = True
model.get_layer('bn5c_branch2c').trainable = True
# Used when compiling the siamese network
def identity_loss(y_true, y_pred):
return K.mean(y_pred - 0 * y_true)
# Create the siamese network
x = model.get_layer('flatten_1').output # layer 'flatten_1' is the last layer of the model
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)
anchor_input = Input(shape=(224, 224, 3), name='anchor_input')
pos_input = Input(shape=(224, 224, 3), name='pos_input')
neg_input = Input(shape=(224, 224, 3), name='neg_input')
encoding_anchor = new_model(anchor_input)
encoding_pos = new_model(pos_input)
encoding_neg = new_model(neg_input)
loss = Lambda(triplet_loss)([encoding_anchor, encoding_pos, encoding_neg])
siamese_network = Model(inputs = [anchor_input, pos_input, neg_input],
outputs = loss) # Note that the output of the model is the
# return value from the triplet_loss function above
siamese_network.compile(optimizer=Adam(lr=.0001), loss=identity_loss)
要注意的一件事是,我将所有批处理规范化层都设置为“可训练的”,以便可以使用我的训练数据更新BN相关的参数。这会产生很多行,但是我找不到更短的解决方案。
答案 0 :(得分:0)
该解决方案的灵感来自@Gurmeet Singh的上述建议。
在训练过程中,可训练图层的权重似乎过了一会儿就变得很大,所有这些权重都设置为NaN,这让我觉得我以错误的方式保存和重新加载模型,但问题是爆炸性的
我在github讨论中也看到了类似的问题,可以在这里查看:github.com/keras-team/keras/issues/2378 在github中该线程的底部,建议使用较低的学习率来避免该问题。
在此链接(Keras ML library: how to do weight clipping after gradient updates? TensorFlow backend)中,讨论了2个解决方案: -使用优化器中的 clipvalue 参数,该参数将按配置简单地剪切计算出的梯度值。但这不是推荐的解决方案。(在另一个线程中进行了解释。) -第二件事是使用clipnorm参数,当用户的L2范数超过给定值时,它会简单地剪切计算出的渐变值。
我还考虑过使用输入归一化(以避免梯度渐变),但后来发现它已经在 preprocess_input(..)函数中完成。 (请查看此链接以获取详细信息:https://www.tensorflow.org/api_docs/python/tf/keras/applications/resnet50/preprocess_input)尽管可以将 mode 参数设置为“ tf” (设置为“ caffe” < / strong>默认情况下是/ strong>),这可能会进一步提供帮助(因为 mode =“ tf” 设置可在-1和1之间缩放像素),但我没有尝试。
我总结一下,在编译将要训练的模型时,我做了两件事:
已更改的行如下:
更改前:
siamese_network.compile(optimizer=Adam(**lr=.0001**),
loss=identity_loss)
更改后:
siamese_network.compile(optimizer=Adam(**lr=.00004**, **clipnorm=1.**),
loss=identity_loss)
1)使用较小的学习率使梯度更新略小 2)使用clipnorm参数归一化计算出的梯度并将其剪切。
然后我再次训练了我的网络10个纪元。损耗按需要降低,但现在更加缓慢。而且在保存和存储模型时我没有遇到任何问题。 (至少经过10个时间段(在我的计算机上需要时间)。)
请注意,我将 clipnorm 的值设置为 1 。这意味着,首先计算梯度的L2范数,如果计算的归一化梯度超过“ 1”的值,则将剪切该梯度。我认为这是一个可以优化的超参数,它会影响模型训练所需的时间,同时有助于避免爆炸梯度问题。