Python 如何使用 numpy 数组在 Keras 中设置权重?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47183159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:03:35  来源:igfitidea点击:

How to set weights in Keras with a numpy array?

pythontensorflowmachine-learningkerasdeep-learning

提问by DeltaLee

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.

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

I have tried...

我试过了...

Loading an existing model

加载现有模型

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]

Creating a simple model

创建一个简单的模型

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]

Then using set_weights or set_value

然后使用 set_weights 或 set_value

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

or...

或者...

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)]

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

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

回答by Daniel M?ller

What is keras_layerin your code?

什么是keras_layer你的代码?

You can set weights these ways:

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

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

Where modelis 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.

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

回答by Palak

The set_weights() method of keras accepts a list of numpy arrays, what you have passed to the method seems like a single array. The shape of this should be the same as the shape of the output of get_weights() on the same layer. Here's the code:

keras 的 set_weights() 方法接受一个 numpy 数组列表,您传递给该方法的内容似乎是单个数组。this 的形状应该与 get_weights() 在同一层上的输出形状相同。这是代码:

l=[]
x=np.array() #weights
y=np.array() #array of biases
l.append(x)
l.append(y)
loaded_model.layers[0].set_weights(l) #loaded_model.layer[0] being the layer

This worked for me and it returns the updated weights on calling get_weights().

这对我有用,它在调用 get_weights() 时返回更新的权重。

回答by nerox8664

If you are trying to convert Pytorch model to Keras model, you can also try a Pytorch2Kerasconverter.

如果您正在尝试将 Pytorch 模型转换为 Keras 模型,您也可以尝试使用Pytorch2Keras转换器。

It supports base layers like Conv2d, Linear, Activations, some element-wise operations etc. You can follow pytorch2keras/layers.pyfor layer convertion functions.

它支持基础层,如 Conv2d、Linear、Activations、一些元素操作等。您可以关注pytorch2keras/layers.py层转换功能。