Keras的模型是用hdf5存儲的,如果想要查看模型,keras提供了get_weights的函數可以查看:
for layer in model.layers:
weights = layer.get_weights() # list of numpy array
而通過hdf5模塊也可以讀取:hdf5的數據結構主要是File - Group - Dataset三級,具體操作API可以看官方文檔。weights的tensor保存在Dataset的value中,而每一集都會有attrs保存各網絡層的屬性:
import h5py
def print_keras_wegiths(weight_file_path):
f = h5py.File(weight_file_path) # 讀取weights h5文件返回File類
try:
if len(f.attrs.items()):
print("{} contains: ".format(weight_file_path))
print("Root attributes:")
for key, value in f.attrs.items():
print(" {}: {}".format(key, value)) # 輸出儲存在File類中的attrs信息,一般是各層的名稱
for layer, g in f.items(): # 讀取各層的名稱以及包含層信息的Group類
print(" {}".format(layer))
print(" Attributes:")
for key, value in g.attrs.items(): # 輸出儲存在Group類中的attrs信息,一般是各層的weights和bias及他們的名稱
print(" {}: {}".format(key, value))
print(" Dataset:")
for name, d in g.items(): # 讀取各層儲存具體信息的Dataset類
print(" {}: {}".format(name, d.value.shape)) # 輸出儲存在Dataset中的層名稱和權重,也可以打印dataset的attrs,但是keras中是空的
print(" {}: {}".format(name. d.value))
finally:
f.close()
而如果想修改某個值,則需要通過新建File類,然后用create_group, create_dataset函數將信息重新寫入,具體操作可以查看這篇文章
參考
- http://download.nexusformat.org/sphinx/examples/h5py/index.html
- https://github.com/fchollet/keras/issues/91
- http://christopherlovell.co.uk/blog/2016/04/27/h5py-intro.html
- http://docs.h5py.org/en/latest/quick.html
- https://confluence.slac.stanford.edu/display/PSDM/How+to+access+HDF5+data+from+Python#HowtoaccessHDF5datafromPython-Example2:Extractandprintthetimevariables
