繁体   English   中英

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

[英]How to set custom weights on a Keras Sequential Model?

所以,我想设置我自己的权重的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。

为什么会这样呢?

形状未对齐。

您最好这样做:

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)

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM