如何在Keras顺序模型上设置自定义权重?

时间:2019-04-12 02:41:07

标签: python tensorflow keras

因此,我想自行为Sequential keras模型设置权重。为了获得权数,我将相邻层的节点数彼此相乘。

这是我的代码:

model.add(Dense(units=3, activation='relu', input_dim=4))
model.add(Dense(3, activation='relu'))
model.add(Dense(5, activation='softmax'))

weights_count = []

weights_count.append(4*3)
weights_count.append(3*3)
weights_count.append(3*5)

weights = []

for count in weights_count:
    curr_weights = []
    for i in range(count):
        curr_weights.append(random.random())
    weights.append(curr_weights)
model.set_weights(weights)

此代码生成此错误:

  

ValueError:形状必须相等,但对于输入形状为[4,3],[12]的“分配”(操作:“分配”),形状必须为2和1。

为什么会这样?

1 个答案:

答案 0 :(得分:2)

形状未对齐。

您最好这样做:

import numpy as np

# create weights with the right shape, e.g.
weights = [np.random.rand(*w.shape) for w in model.get_weights()]

# update
model.set_weights(weights)

希望有帮助。