我像这样使用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')