我對 tf.keras.constraints 方法有疑問。
(1)
class WeightsSumOne(tf.keras.constraints.Constraint):
def __call__(self, w):
return tf.nn.softmax(w, axis=0)
output = layers.Dense(1, use_bias=False,
kernel_constraint = WeightsSumOne())(input)
(2)
intermediate = layers.Dense(1, use_bias = False)
intermediate.set_weights(tf.nn.softmax(intermediate.get_weights(), axis=0))
(1) 和 (2) 是否執行相同的程序?
我問這個問題的原因是 Keras Documentation 說
它們是在每次梯度更新后(使用 fit() 時)應用于目標變數的每變數投影函式。( https://keras.io/api/layers/constraints/ )
與(1)不同,我認為在(2)的情況下,約束是在每次梯度更新之前應用的。
在我看來,(1)和(2)的權重梯度是不同的,因為softmax是在第二種情況下梯度計算之前應用的,但是在第一種情況下梯度計算之后應用的。
如果我錯了,如果您指出錯誤的部分,我將不勝感激。
uj5u.com熱心網友回復:
他們不一樣。
在第一種情況下,約束應用于層,weights但在第二種情況下,它應用于dense層的輸出(在與輸入相乘之后)。
在第一種情況下構建模型:
inp = keras.Input(shape=(3,5))
out = keras.layers.Dense(1, use_bias=False, kernel_initializer=tf.ones_initializer(),
kernel_constraint= WeightsSumOne())(inp)
model = keras.Model(inp, out)
model.compile('adam', 'mse')
假跑,
inputs = tf.random.normal(shape=(1,3,5))
outputs = tf.random.normal(shape=(1,3,1))
model.fit(inputs,outputs, epochs=1)
檢查層權重model
print(model.layers[1].get_weights()[0])
#outputs
array([[0.2],
[0.2],
[0.2],
[0.2],
[0.2]]
在第二種情況下構建模型
inp = keras.Input(shape=(3,5))
out = keras.layers.Dense(1, activation='softmax', use_bias=False,
kernel_initializer=tf.ones_initializer())(inp)
model1 = keras.Model(inp, out)
model1.compile('adam', 'mse')
#dummy run
model1.fit(inputs,outputs, epochs=1)
檢查模型1的層權重,
print(model1.layers[1].get_weights()[0])
#outputs
array([[1.],
[1.],
[1.],
[1.],
[1.]],
我們可以看到layer weight of model是softmaxlayer weight of model1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/526967.html
標籤:张量流喀拉斯
上一篇:C#winform使用NOPI讀取Excel讀取圖片
下一篇:如何填充所有張量以適應所有尺寸
