在keras的卷积层中从数组设置权重

时间:2018-12-17 18:23:38

标签: python tensorflow keras

我需要帮助为2D卷积层的Keras模型设置权重。我正在使用tensorflow作为后端。我有一个看起来像这样的数组:

x=np.array([[[[-0.0015705, 0.00116176, 0.06618503, 0.03435471]],
[[0.00521054,0.02447471,-0.05024014,-0.04470699]],
[[0.10342247,0.120496,-0.12113544, -0.09823987]]],

[[[ -0.07988621,-0.08923271, 0.06095106, 0.06129697]],
[[0.02397859,0.01935878,0.07312153,0.04485333]],
[[0.0560354,0.06753333, -0.12324878, -0.12986778]]], 

[[[-0.08374127,-0.09646999,0.08217654, 0.09985162]],
[[-0.02354228,-0.0587804,0.02877157, 0.0338508]],
[[0.01338571, 0.01647802, -0.05392551, -0.08461332]]]], dtype=float)

现在我已经尝试过了,

def cnn_model(result_class_size):
    model = Sequential()
    model.add(Conv2D(4, (3, 3), input_shape=(28,28,1), activation='relu'))
    model.add(Flatten())
    model.add(Dense(result_class_size, activation='softmax'))   
    model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
    return model

df_train_x = df_train.iloc[:,1:]  #get 784 pixel value columns after the first column
df_train_y = df_train.iloc[:,:1]

arr_train_y = np_utils.to_categorical(df_train_y['label'].values)
model = cnn_model(arr_train_y.shape[1])
model.summary()

df_train_x = df_train_x / 255 # normalize the inputs
#reshape training X to (number, height, width, channel)
arr_train_x_28x28 = np.reshape(df_train_x.values, (df_train_x.values.shape[0], 28, 28, 1))
model.fit(arr_train_x_28x28, arr_train_y, epochs=1, batch_size=100)

# displaying the random image which is inputed
test_index = randrange(df_train_x.shape[0])
test_img = arr_train_x_28x28[test_index]
plt.imshow(test_img.reshape(28,28), cmap='gray')
plt.title("Index:[{}] Value:{}".format(test_index, df_train_y.values[test_index]))
plt.show()
a = np.array(model.layers[0].get_weights())
model.layers[0].set_weights(x)
print("after changing weights")
print(model.layers[0].get_weights()) 

但这给我一个错误,

ValueError: You called `set_weights(weights)` on layer "conv2d_1" with a  weight list of length 36, but the layer was expecting 2 weights. Provided weights: [-0.0015705   0.00116176  0.06618503  0.03435471  ...

2 个答案:

答案 0 :(得分:0)

您需要一个包含[weights, biases]的列表,该列表与get_weights()中的列表完全相同

答案 1 :(得分:0)

在keras模型中,应该在数组中设置偏差值。例如:

x = [np.ones(shape = LayerShape, dtype = 'float32'), np.zeros(shape = LayerLength, dtype = 'float32')]

现在您可以将x设置为图层权重

dis.layers[0].set_weights(x)
print(dis.layers[0].get_weights())

它的输出:

[array([[1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.],
   ...,
   [1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.]], dtype=float32), array([0., 0., 0., ..., 0., 0., 0.], dtype=float32)]