如何将hdf5文件的内容复制到文本文件

时间:2018-08-30 20:05:19

标签: python hdf5

我已将模型的权重保存在hdf5文件中。该文件包含以下内容:

[u'model_weights', u'optimizer_weights']

我希望能够将所有的砝码逐行打印到文本文件中。我该怎么办?

Edit1:

最近发现了如何打印整个键/组。这是完整的信息

FILE_CONTENTS {
 group      /
 group      /model_weights
 group      /model_weights/concatenate_1
 group      /model_weights/conv1d_1
 group      /model_weights/conv1d_1/conv1d_1
 dataset    /model_weights/conv1d_1/conv1d_1/bias:0
 dataset    /model_weights/conv1d_1/conv1d_1/kernel:0
 group      /model_weights/conv1d_2
 group      /model_weights/conv1d_2/conv1d_2
 dataset    /model_weights/conv1d_2/conv1d_2/bias:0
 dataset    /model_weights/conv1d_2/conv1d_2/kernel:0
 group      /model_weights/conv1d_3
 group      /model_weights/conv1d_3/conv1d_3
 dataset    /model_weights/conv1d_3/conv1d_3/bias:0
 dataset    /model_weights/conv1d_3/conv1d_3/kernel:0
 group      /model_weights/dense_1
 group      /model_weights/dense_1/dense_1
 dataset    /model_weights/dense_1/dense_1/bias:0
 dataset    /model_weights/dense_1/dense_1/kernel:0
 group      /model_weights/dropout_1
 group      /model_weights/flatten_1
 group      /model_weights/flatten_2
 group      /model_weights/flatten_3
 group      /model_weights/input_1
 group      /model_weights/max_pooling1d_1
 group      /model_weights/max_pooling1d_2
 group      /model_weights/max_pooling1d_3
 group      /optimizer_weights
 dataset    /optimizer_weights/Variable:0
 dataset    /optimizer_weights/Variable_10:0
 dataset    /optimizer_weights/Variable_11:0
 dataset    /optimizer_weights/Variable_12:0
 dataset    /optimizer_weights/Variable_13:0
 dataset    /optimizer_weights/Variable_14:0
 dataset    /optimizer_weights/Variable_15:0
 dataset    /optimizer_weights/Variable_1:0
 dataset    /optimizer_weights/Variable_2:0
 dataset    /optimizer_weights/Variable_3:0
 dataset    /optimizer_weights/Variable_4:0
 dataset    /optimizer_weights/Variable_5:0
 dataset    /optimizer_weights/Variable_6:0
 dataset    /optimizer_weights/Variable_7:0
 dataset    /optimizer_weights/Variable_8:0
 dataset    /optimizer_weights/Variable_9:0
 dataset    /optimizer_weights/iterations:0
 }
}

2 个答案:

答案 0 :(得分:0)

with open(hdf5_file) as fin:
    for line in fin:
        line = line.strip()[1:-1] # assume you have [u'model_weights', u'optimizer_weights'] in each line
        print '\n'.join(line.split(','))

答案 1 :(得分:0)

from keras.models import load_model
file_to_open = "your_file.h5"
f = h5py.File(file_to_open, 'r')
model = load_model(file_to_open)
for layer in model.layers:

    g=layer.get_config()
    h=layer.get_weights()
    print (g)
    print (h)