首页 > 解决方案 > 从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  ...

标签: pythontensorflowkeras

解决方案


你需要一个列表[weights, biases],和出来的完全一样get_weights()


推荐阅读