如何修复 (“ValueError: 你试图将包含16个层的权重文件加载到一个包含0个层的模型中”)

我像这样使用vgg16:

model = VGG16()data, labels = ReadImages(TRAIN_DIR)vgg16 = VGG16()model = Sequential()#将VGG16转换为Sequential模型for layer in vgg16.layers[:-1]:    model.add(layer)#冻结除最后一层以外的所有层以进行迁移学习for layer in model.layers:    layer.trainable = False#添加自定义的softmax层model.add(Dense(1,activation='sigmoid'))#编译我们的模型model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])model.fit(np.array(data), np.array(labels), batch_size=32, epochs=3)model.save('model.h5')

当我在另一个py文件中尝试加载这个模型时..:

model = load_model('model.h5')

我已经尝试过使用load_weights,但也抛出了错误

… 返回这个错误:

ValueError: You are trying to load a weight file containing 16 layers into a model with 0 layers

我该怎么做才能加载这个模型来进行预测呢?

版本: keras 2.2.4 tensorflow 1.14.0


回答:

已知问题: https://github.com/keras-team/keras/issues/10417

有三种选择: 1. 重新创建模型架构并使用 ‘load_weights‘。如果您只想进行预测,这是个好方法。 2. 降级到Keras版本 2.1.6。 3. 在此链接中有一个解决方案 https://github.com/keras-team/keras/issues/10417#issuecomment-435620108。我为VGG16适应了这个解决方案。这会更新h5文件。

def fix_layer0(filename, batch_input_shape, dtype):    with h5py.File(filename, 'r+') as f:        model_config = json.loads(f.attrs['model_config'].decode('utf-8'))        layer0 = model_config['config']['layers'][0]['config']        layer0['batch_input_shape'] = batch_input_shape        layer0['dtype'] = dtype        f.attrs['model_config'] = json.dumps(model_config).encode('utf-8')fix_layer0('model.h5', [None, 224, 224, 3], 'float32')loaded_model = load_model('model.h5')

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注