python - 如何在 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: Shapes must be equal rank, but are 2 and 1 for 'Assign' (op: 'Assign') with input shapes: [4,3], [12].
为什么会这样?
解决方案
形状未对齐。
你可能会更好地做这样的事情:
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)
希望有帮助。
推荐阅读
- symfony - 表单被刷新,而不是在 EasyAdmin (Symfony) 中返回错误
- python - Python - 从 yaml 获取所有 url
- visual-studio-code - VSCode 在启动时冻结
- google-bigquery - BigQuery REGEXP_REPLACE 在替换表达式中引用捕获组
- excel - 有没有办法在 Power BI 的“折线和聚集柱形图”中使用我的左 Y 轴包含趋势线?
- arrays - 我正在使用 for 循环添加两个数组。只有我的第二个数组的第一个元素被添加到第一个数组的所有元素中。For循环没有迭代
- database - 无法使用 Robo3T 连接到 Mongo 副本集
- python - 在python中将任何类型更改为字节
- html - 仪表板网格替代方案
- mysql - 设计新的表结构,需要idea