当我运行以下代码时
from tensorflow import keras import numpy as npx = np.ones((1,2,1))model = keras.models.Sequential()model.add(keras.layers.GRU( units = 1, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='ones', recurrent_initializer='ones',bias_initializer='zeros', return_sequences = True))model.predict(x)
我得到的输出是=> array([[[0.20482421], [0.34675306]]], dtype=float32)
当我手动计算时,我得到的是0.55
假设没有偏置且所有权重都设置为1
hidden_(t-1) = 0
更新门 = sigmoid(1×1 + 1×0) = 0.73
相关门 = sigmoid(1×1 + 1×0) = 0.73
候选h(t) = tanh( 1 x (0 x 0.73) + 1 x 1) = tanh(1) = 0.76
h(t) = 0.73*0.76 + (1 – 0.73)x0 = 0.55
那么输出的第一个值不应该是0.55吗?
回答:
你似乎在最后一行的隐藏状态方程中弄错了。
sigmoid(1 * 1 + 1 * 0) = 0.73105857863, tanh(1 * 1 + 1 * 0) = 0.761594155956
Ht = Zt ⊙ Ht-1 + (1 – Zt) ⊙ H~t
由于Ht-1 = 0,因此得到Ht = (1 – Zt) ⊙ H~t
根据GRU公式,我计算得出h(t) = 0.73105857863 * 0 + (1 - 0.73105857863) x 0.761594155956 = 0.20482421480989209117972
,这与输出0.20482421
相符。
对于下一个时间步,
Rt = Sigmoid(1 * 1 + 1 * 0.20482421) = 0.769381871687
Zt = Sigmoid(1 * 1 + 1 * 0.20482421) = 0.769381871687
H~t = tanh(1 * 1 + 0.769381871687 * 0.20482421 * 1) = 0.8202522791
Ht = 0.769381871687 * 0.20482421 + (1 – 0.769381871687) * 0.8202522791 = 0.346753079407
这与最终输出0.34675306
相符。
参考资料,
https://d2l.ai/chapter_recurrent-modern/gru.html#hidden-state