簡體   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