Python keras 中的只读模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53212672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read only mode in keras
提问by Debadri Chowdhury
I have cloned human pose estimation keras model from this link human pose estimation keras
我已经从这个链接中克隆了人体姿势估计 keras 模型人体姿势估计 keras
When I try to load the model on google colab, I get the following error
当我尝试在 google colab 上加载模型时,出现以下错误
code
代码
from keras.models import load_model
model = load_model('model.h5')
error
错误
ValueError Traceback (most recent call
last)
<ipython-input-29-bdcc7d8d338b> in <module>()
1 from keras.models import load_model
----> 2 model = load_model('model.h5')
/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py in load_model(filepath, custom_objects, compile)
417 f = h5dict(filepath, 'r')
418 try:
--> 419 model = _deserialize_model(f, custom_objects, compile)
420 finally:
421 if opened_new_file:
/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py in _deserialize_model(f, custom_objects, compile)
219 return obj
220
--> 221 model_config = f['model_config']
222 if model_config is None:
223 raise ValueError('No model found in config.')
/usr/local/lib/python3.6/dist-packages/keras/utils/io_utils.py in __getitem__(self, attr)
300 else:
301 if self.read_only:
--> 302 raise ValueError('Cannot create group in read only mode.')
303 val = H5Dict(self.data.create_group(attr))
304 return val
ValueError: Cannot create group in read only mode.
Can someone please help me understand this read-only mode? How do I load this model?
有人可以帮我理解这种只读模式吗?我如何加载这个模型?
采纳答案by Konstantin Grigorov
Here is an example Git gist created on Google Collab for you: https://gist.github.com/kolygri/835ccea6b87089fbfd64395c3895c01f
以下是在 Google Collab 上为您创建的 Git 要点示例:https: //gist.github.com/kolygri/835ccea6b87089fbfd64395c3895c01f
As far as I understand:
据我所理解:
You have to set and define the architecture of your model and then use model.load_weights('alexnet_weights.h5').
您必须设置和定义模型的架构,然后使用 model.load_weights('alexnet_weights.h5')。
Here is a useful Github conversation link, which hopefully will help you understand the issue better: https://github.com/keras-team/keras/issues/6937
这是一个有用的 Github 对话链接,希望能帮助您更好地理解问题:https: //github.com/keras-team/keras/issues/6937
回答by Akhilesh_IN
I had a similar issue and solved this way
我有一个类似的问题,并以这种方式解决
storethe graph\architecturein JSONformat and weightsin h5format
存储的graph\architecture在JSON格式和weights中h5格式
import json
# lets assume `model` is main model
model_json = model.to_json()
with open("model_in_json.json", "w") as json_file:
json.dump(model_json, json_file)
model.save_weights("model_weights.h5")
then need to load modelfirst to creategraph\architectureand load_weightsin model
这时需要load model先creategraph\architecture和load_weights模型
from keras.models import load_model
from keras.models import model_from_json
import json
with open('model_in_json.json','r') as f:
model_json = json.load(f)
model = model_from_json(model_json)
model.load_weights('model_weights.h5')
回答by handhand
I used callbacks.ModelCheckpointto save the weights and I had a similar error. I found out that there is a parameter called save_weights_only
我曾经callbacks.ModelCheckpoint保存权重,但也有类似的错误。我发现有一个参数叫做save_weights_only
If I set save_weights_only=True, then when I use load_model() to load the model in another process, it will raise the 'Cannot create group in read only mode.' error.
如果我设置了save_weights_only=True,那么当我使用 load_model() 在另一个进程中加载模型时,它会引发“无法在只读模式下创建组”。错误。
If I set save_weights_only=False(which is the default), then I can use load_model() to load the model and use it to do prediction, without compiling the model first.
如果我设置save_weights_only=False(这是默认设置),那么我可以使用 load_model() 加载模型并使用它进行预测,而无需先编译模型。
回答by Guinther Kovalski
you can use model.save(model_path+'Model.h5')and then keras.models.load_model(model_path+'Model.h5'), this way, you will not need to build and compile the model before load the weights, as model.savecreates the architecture in dict inside the .h5file.
您可以使用model.save(model_path+'Model.h5')然后keras.models.load_model(model_path+'Model.h5'),这样,您将不需要在加载权重之前构建和编译模型,因为model.save在.h5文件内的 dict 中创建了架构。
回答by Mudaser Ali
Easy solution is you have to load the save model in the same way it is saved
简单的解决方案是您必须以与保存模型相同的方式加载保存模型
for example you had created a model like this
例如你已经创建了一个这样的模型
# Build the model
model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
#fit the model
model.fit(x_train, y_train,
batch_size=10,
epochs=5,
verbose=1,
validation_split=0.1)
#save model
model.save("model.h5")
so if you want to load this model for prediction you have to follow the same steps
所以如果你想加载这个模型进行预测,你必须遵循相同的步骤
from keras.models import load_model
# Build the model
model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# load model
model.load_weights('model.h5')
prediction = model.predict( ''' data to predict ''')

