python - 从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 ...
解决方案
你需要一个列表[weights, biases]
,和出来的完全一样get_weights()
推荐阅读
- javascript - 在使用 create-react-app 制作的 reactjs 应用程序中,如何在项目目录结构之外的文件中导入 js 模块?
- mongodb - 在投影中使用 $elemMatch 并选择字段
- python - 多路复用两个流后如何提高RTMP流的音频质量
- powershell - perl 执行系统命令而不进行插值
- python - 我想删除在 aws lambda 的 xml 输出中引入的反斜杠。我的代码在python中
- javascript - 无法将图像高度和宽度分配给打字稿中的输入类型框
- c# - 如何在下拉列表的视图中显示类的变量(IN MVC 模型)
- postgresql - 如何从 postgres 选择查询中返回数组?
- python - 如何在 matplotlib 的嵌套饼图中使用正确的 cmap 颜色
- python - 如何使用汤从页面中提取列中的数据