首页 > 解决方案 > hdf5 文件中的权重和偏差

问题描述

我正在使用 Keras 和 Tensorflow 来训练神经网络。通过提前停止回调,我正在保存包含权重和偏差的 hdf5 文件:

file_path = "data/weights-improvement-{epoch:02d}-{val_loss:.2f}.hdf5"

save_best_callback = ModelCheckpoint(file_path, monitor='val_loss', verbose=1, save_best_only=True,
                                     save_weights_only=False, mode='auto', period=1)


# model
visible = Input(shape=(36,))

x = Dense(40, activation='tanh')(visible) 
x = Dense(45, activation='tanh')(x) 
x = Dense(30, activation='tanh')(x) 
x = Dense(55, activation='tanh')(x)

output = Dense(5, activation='tanh')(x)

通常,我使用

weights_1 = model.layers[1].get_weights()[0]
biases_1 = model.layers[1].get_weights()[1]

一层。

不知何故,当我一夜之间运行我的脚本时,权重和偏差无法保存(这很不寻常,未能创建 hdf5 文件)。现在我有多个 hdf5 文件,我想从中选择最后一个可以保存的文件来加载我的权重和偏差。

我希望每一层的权重矩阵具有形式(#cells x #inputs)和偏置矩阵具有形式(#cells x 1),而对于层 j=1 #inputs = 36 和 j>1 输入= #细胞(j-1)。然后这些矩阵应该存储为 numpy 数组。

我总共有 5 层,这应该给我 5 个权重和偏差矩阵。我尝试用 pandas 加载 hdf5 文件:

import numpy as np
import pandas as pd

array = np.fromfile('data/weights-improvement-446-0.00.hdf5', dtype=float)
df_array = pd.DataFrame(array)
print(df_array)

但这只是给了我一个由 1 列和 m 行组成的数据框,其中一些元素是“NaN”。谁能帮我?提前致谢。

标签: pythontensorflowkerashdf5

解决方案


为什么不使用 keras load_model API?如果只是权重,请使用 load_weights API。

>>> from keras.models import load_model
>>> model = load_model('data/weights-improvement-446-0.00.hdf5')
>>> for layer in model.layers:
>>>     if len(layer.weights) > 0:
>>>         print(layer.name, layer.weights[0].shape)

推荐阅读