簡體   English   中英

如何在沒有模型的情況下讀取keras模型權重

[英]How to read keras model weights without a model

keras模型可以保存在兩個文件中。 一個文件具有模型體系結構。 另一個是模型權重,權重由方法model.save_weights()保存。

然后可以使用model.load_weights(file_path)加載權重。 它假定模型存在。

我只需要加載沒有模型的權重。 我試着用pickle.load()

with open(file_path, 'rb') as fp:
    w = pickle.load(fp)

但它給出了錯誤:

_pickle.UnpicklingError: invalid load key, 'H'.

我認為權重文件以不兼容的方式保存。 是否可以從model.save_weights()創建的文件中僅加載權重?

數據格式為h5,因此您可以直接使用h5py庫來檢查和加載權重。 快速入門指南

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.

該文件包含屬性,包括圖層的權重,您可以詳細探索存儲的內容和方式。 如果你想要一個可視版本,那么也有h5pyViewer

參考: 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')

您需要創建一個Keras Model ,然后您可以加載您的architecture ,然后加載model weights

請參閱下面的代碼,

model = keras.models.Sequential()          # create a Keras Model
model.load_weights('my_model_weights.h5')  # load model weights

Keras文檔中的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM