首页 > 解决方案 > 如何在 Keras 序列模型上设置自定义权重?

问题描述

所以我想自己为Sequentialkeras 模型设置权重。为了获得权重的数量,我将相邻层的节点数相乘。

这是我的代码:

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: Shapes must be equal rank, but are 2 and 1 for 'Assign' (op: 'Assign') with input shapes: [4,3], [12].

为什么会这样?

标签: pythontensorflowkeras

解决方案


形状未对齐。

你可能会更好地做这样的事情:

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)

希望有帮助。


推荐阅读