python - 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”。谁能帮我?提前致谢。
解决方案
为什么不使用 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)
推荐阅读
- postgresql - 监控 Postgres 上的查询
- python - 为什么我的字计数器在我第一次运行时产生的输出与第二次不同?
- c# - 使用 C# 在 SQL Server 中增加一年后月份不增加
- node.js - 使用 Homebrew 在 macOS 上安装 node.js + npm 会防止 EACCES 权限错误吗?
- android - 在 RxJava 中“加入”一个 Observable 列表
- java - 为什么 JIT 编译器不提前编译字节码?
- php - 在 try-catch 块中省略 $ex 变量
- c++ - 如果您在循环内给 cin 一个意外的输入,C++ 换行符会自动作为输入输入
- python-3.x - 如何在 Python 中使用 MPI 在不同的内核上实现简单的并行计算
- javascript - 纯JS的表单验证