tensorflow - 如何加载微调的keras模型

标签 tensorflow keras

我正在关注this尝试使用 VGG16 模型进行微调的教程,我训练了模型并使用 model.save_weights

保存了 .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()

我认为这样做的好处是不必重建模型,并且只需要一行即可完成相同的目的。

关于tensorflow - 如何加载微调的keras模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58693138/

相关文章:

python - 将具有许多二进制数据特征的大量观察结果输入 TensorFlow

python - Tensorflow:从大于 2 GB 的 numpy 数组创建小批量

python - 如何使用 Keras GRU 在多参数天气时间序列上实际预测一个参数

tensorflow - 序列元素打乱后的奇怪序列分类性能

python - Keras 拟合模型 : TypeError: unhashable type: 'numpy.ndarray'

python - 为 Keras 逐个元素编写自定义损失函数

python - 将可变长度列表数据(来自 csv)分配给 'indicator_column' 特征

python - “DNN”对象在 ImageDataGenerator() 中没有属性 'fit_generator' - keras - python

tensorflow - 图像分类 : Heavily unbalanced data over thousands of classes

python - Keras ImageDataGenerator 和 flow_from_directory class_mode ='input'