如何使用一个numpy数组在Keras中设置权重? [英] How to set weights in Keras with a numpy array?
问题描述
我在设置值的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)]
我如何在keras中使用数值数组来设置图层的权重?
How do I set the weights of a layer in Keras with a numpy array of values?
推荐答案
代码中的keras_layer
是什么?
您可以通过以下方式设置权重:
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屋!