Tensorflow 如何加载微调keras模型
我遵循教程尝试使用VGG16模型进行微调,我训练了模型并使用Tensorflow 如何加载微调keras模型,tensorflow,keras,Tensorflow,Keras,我遵循教程尝试使用VGG16模型进行微调,我训练了模型并使用模型保存.h5文件。保存权重和 vgg_conv = VGG16(include_top=False, weights='imagenet', input_shape=(image_size, image_size, 3)) # Freeze the layers except the last 4 layers for layer in vgg_conv.layers[:-4]: layer.trai
模型保存.h5
文件。保存权重
和
vgg_conv = VGG16(include_top=False, weights='imagenet', input_shape=(image_size, image_size, 3))
# Freeze the layers except the last 4 layers
for layer in vgg_conv.layers[:-4]:
layer.trainable = False
model = Sequential()
model.add(vgg_conv)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(11, activation='softmax'))
然后,我尝试使用下面的方法重建架构和负载权重
def create_model(self):
model = Sequential()
vgg_model = VGG16(include_top=False, weights='imagenet', input_shape=(150, 150, 3))
model.add(vgg_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(11, activation='softmax'))
model.load_weights(self.top_model_weights_path) # throws error
return model
但它随后抛出了这个错误
ValueError: Cannot feed value of shape (512, 512, 3, 3) for Tensor 'Placeholder:0', which has shape '(3, 3, 3, 64)'
我做错了什么?我不知道如何解释错误,但您可以尝试在微调后将模型架构和权重一起保存
model.save(“model.h5”)
要加载模型,可以键入
model = load_model('model.h5')
# summarize model.
model.summary()
我认为这样做的好处是不必重建模型,只需要一条生产线就可以实现相同的目的。问题来自于两种模型之间可培训的差异。如果在“创建模型”功能中冻结最后4个层,它将起作用
但正如Igna所说,model.save和model.load_模型更简单。它起作用了,但您能否详细说明答案?我不认为冻结会影响所需的张量形状我不知道为什么,我只是认为这是唯一的区别。想知道“保存重量”是否只保存可训练重量。答案当然在代码中。您还可以尝试使用model.load\u weights(filepath,by\u name=False)函数的“by\u name”选项。我怀疑最后4层的权重没有保存,也没有恢复。运行一些测试来验证这一点是值得的。我想知道这是否是一个bug。我查看了不同模型的权重,根据冻结参数的层数,列出时层数的顺序不同:for layer in model.layers:print(layer.weights),但层数完全相同,只是顺序不同。