如何使用 numpy 数组在 Keras 中设置权重? [英] How to set weights in Keras with a numpy array?

查看:31
本文介绍了如何使用 numpy 数组在 Keras 中设置权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Keras 后端函数设置值时遇到问题.我正在尝试将模型从 PyTorch 转换为 Keras 并尝试设置 Keras 模型的权重,但权重似乎没有设置.注意:我实际上并没有使用 np.ones 进行设置,只是将其用作示例.

I am having trouble with the Keras backend functions for setting values. I am trying to convert a model from PyTorch to Keras and am trying to set the weights of the Keras model, but the weights do not appear to be getting set. Note: I am not actually setting with np.ones just using that for an example.

我试过了...

加载现有模型

import keras
from keras.models import load_model, Model
model = load_model(model_dir+file_name)
keras_layer = [layer for layer in model.layers if layer.name=='conv2d_1'][0]

创建一个简单的模型

img_input = keras.layers.Input(shape=(3,3,3))
x = keras.layers.Conv2D(1, kernel_size=1, strides=1, padding="valid", 
use_bias=False, name='conv1')(img_input)
model = Model(img_input, x)
keras_layer = [layer for layer in model.layers if layer.name=='conv1'][0]

然后使用 set_weights 或 set_value

Then using set_weights or set_value

keras_layer.set_weights([np.ones((1, 1, 3, 1))])

或...

K.batch_set_value([(weight,np.ones((1, 1, 3, 1))) for weight in keras_layer.weights])

之后我调用以下任一方法:

afterwards I call either one of the following:

K.batch_get_value([weight for weight in keras_layer.weights])
keras_layer.get_weights()

而且似乎没有设置任何权重.返回与之前相同的值.

And None of the weights appear to have been set. The same values as before are returned.

[array([[[[  1.61547325e-06],
      [  2.97779252e-06],
      [  1.50160542e-06]]]], dtype=float32)]

如何使用 numpy 值数组在 Keras 中设置层的权重?

How do I set the weights of a layer in Keras with a numpy array of values?

推荐答案

你的代码中的 keras_layer 是什么?

What is keras_layer in your code?

您可以通过以下方式设置权重:

You can set weights these ways:

model.layers[i].set_weights(listOfNumpyArrays)    
model.get_layer(layerName).set_weights(...)
model.set_weights(listOfNumpyArrays)

其中 model 是现有模型的实例.您可以使用上述相同实例中的 get_weights() 方法查看列表的预期长度及其数组形状.

Where model is an instance of an existing model. You can see the expected length of the list and its array shapes using the method get_weights() from the same instances above.

这篇关于如何使用 numpy 数组在 Keras 中设置权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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