Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - How to set weights in Keras with a numpy array?

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...