我正在使用 Keras Lambda 層使用可訓練權重的張量(或至少應該這樣做)進行一些操作;為此,我選擇了一個 tf.Variable 作為引數,但盡管 trainable=True,但摘要顯示 0 個可訓練引數。
weights = tf.Variable(initial_value=tf.random.normal((300,)), trainable=True)
custom_layer = keras.layers.Lambda(custom_func)((input_layer, weights))
獨立于 trainable=True,權重仍然是不可訓練的。另一種選擇是使用如下圖層:
weights = Dense(300, activation='linear', use_bias=False)
在這種情況下,我在 custom_func 中遇到了麻煩,因為 tf.math.multiply 不接受,至少根據我的實驗,Dense 層引數以任何方式(我試過 .get_weights() 和 .variables)。
非常歡迎獲得可訓練權重張量的每個解決方案,提前致謝。
uj5u.com熱心網友回復:
將變數與 lambda 函式一起使用會導致錯誤,因為custom_layer它不能直接跟蹤,weights因此張量不會出現在可訓練的權重中。
這可以通過子Layer類化類來解決,如下所示:
class custom_layer(tf.keras.layers.Layer):
def __init__(self):
super(custom_layer, self).__init__()
self.weights = tf.Variable(...) #define weights here
def call(self, inputs):
return custom_func(..)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/392990.html
標籤:Python 张量流 凯拉斯 keras文件 keras层
上一篇:如何將多張表的內容合二為一?
