如何在没有模型的情况下读取keras模型权重 [英] How to read keras model weights without a model

查看:412
本文介绍了如何在没有模型的情况下读取keras模型权重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个keras模型可以保存在两个文件中.一个文件带有模型体系结构.另一个是模型权重,权重通过方法model.save_weights()保存.

A keras model can be saved in two files. One file is with a model architecture. And the other one is with model weights, weights are saved by the method model.save_weights().

然后可以用model.load_weights(file_path)加载砝码.假设该模型存在.

Then weights can be loaded with model.load_weights(file_path). It assumes that the model exists.

我只需要加载没有模型的砝码.我尝试使用pickle.load().

I need to load only weights without a model. I tried to use pickle.load().

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

但是它给出了错误:

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

我想权重文件是以不兼容的方式保存的. 是否可以仅从model.save_weights()创建的文件中加载权重?

I suppose that weights file was saved in the way not compatible. Is it possible to load only weights from file created by model.save_weights()?

推荐答案

数据格式为h5,因此您可以直接使用h5py库检查并加载权重.从快速入门指南:

The data format is h5 so you can directly use the h5py library to inspect and load the weights. From the quickstart guide:

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 .

The file contains properties including weights of layers and you can explore in detail what is stored and how. If you would like a visual version there is h5pyViewer as well.

这篇关于如何在没有模型的情况下读取keras模型权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆