[英]How to read keras model weights without a model
A keras model can be saved in two files. keras模型可以保存在两个文件中。 One file is with a model architecture.
一个文件具有模型体系结构。 And the other one is with model weights, weights are saved by the method
model.save_weights()
. 另一个是模型权重,权重由方法
model.save_weights()
保存。
Then weights can be loaded with model.load_weights(file_path)
. 然后可以使用
model.load_weights(file_path)
加载权重。 It assumes that the model exists. 它假定模型存在。
I need to load only weights without a model. 我只需要加载没有模型的权重。 I tried to use
pickle.load()
. 我试着用
pickle.load()
。
with open(file_path, 'rb') as fp:
w = pickle.load(fp)
But it gives the error: 但它给出了错误:
_pickle.UnpicklingError: invalid load key, 'H'.
I suppose that weights file was saved in the way not compatible. 我认为权重文件以不兼容的方式保存。 Is it possible to load only weights from file created by model.save_weights()?
是否可以从model.save_weights()创建的文件中仅加载权重?
The data format is h5 so you can directly use the h5py library to inspect and load the weights. 数据格式为h5,因此您可以直接使用h5py库来检查和加载权重。 From the quickstart guide :
从快速入门指南 :
import h5py
f = h5py.File('weights.h5', 'r')
print(list(f.keys())
# will get a list of layer names which you can use as index
d = f['dense']['dense_1']['kernel:0']
# <HDF5 dataset "kernel:0": shape (128, 1), type "<f4">
d.shape == (128, 1)
d[0] == array([-0.14390108], dtype=float32)
# etc.
The file contains properties including weights of layers and you can explore in detail what is stored and how. 该文件包含属性,包括图层的权重,您可以详细探索存储的内容和方式。 If you would like a visual version there is h5pyViewer as well.
如果你想要一个可视版本,那么也有h5pyViewer 。
Ref: https://github.com/keras-team/keras/issues/91 Code Snippet for your ask below 参考: https : //github.com/keras-team/keras/issues/91下面的问题代码片段
from __future__ import print_function
import h5py
def print_structure(weight_file_path):
"""
Prints out the structure of HDF5 file.
Args:
weight_file_path (str) : Path to the file to analyze
"""
f = h5py.File(weight_file_path)
try:
if len(f.attrs.items()):
print("{} contains: ".format(weight_file_path))
print("Root attributes:")
print(" f.attrs.items(): ")
for key, value in f.attrs.items():
print(" {}: {}".format(key, value))
if len(f.items())==0:
print(" Terminate # len(f.items())==0: ")
return
print(" layer, g in f.items():")
for layer, g in f.items():
print(" {}".format(layer))
print(" g.attrs.items(): Attributes:")
for key, value in g.attrs.items():
print(" {}: {}".format(key, value))
print(" Dataset:")
for p_name in g.keys():
param = g[p_name]
subkeys = param.keys()
print(" Dataset: param.keys():")
for k_name in param.keys():
print(" {}/{}: {}".format(p_name, k_name, param.get(k_name)[:]))
finally:
f.close()
print_structure('weights.h5.keras')
You need to create a Keras Model
, then you can load your architecture
and afterwards the model weights
您需要创建一个
Keras Model
,然后您可以加载您的architecture
,然后加载model weights
See the code below, 请参阅下面的代码,
model = keras.models.Sequential() # create a Keras Model
model.load_weights('my_model_weights.h5') # load model weights
More information in the Keras docs Keras文档中的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.