以下是 Tensorflow 的代码GRUCell
单元显示了当先前的隐藏状态与序列中的当前输入一起提供时获得更新的隐藏状态的典型操作。
def __call__(self, inputs, state, scope=None):
"""Gated recurrent unit (GRU) with nunits cells."""
with vs.variable_scope(scope or type(self).__name__): # "GRUCell"
with vs.variable_scope("Gates"): # Reset gate and update gate.
# We start with bias of 1.0 to not reset and not update.
r, u = array_ops.split(1, 2, _linear([inputs, state],
2 * self._num_units, True, 1.0))
r, u = sigmoid(r), sigmoid(u)
with vs.variable_scope("Candidate"):
c = self._activation(_linear([inputs, r * state],
self._num_units, True))
new_h = u * state + (1 - u) * c
return new_h, new_h
但我没有看到任何weights
and biases
这里。
例如我的理解是r
and u
需要将权重和偏差与当前输入和/或隐藏状态相乘以获得更新的隐藏状态。
我写了一个gru单元如下:
def gru_unit(previous_hidden_state, x):
r = tf.sigmoid(tf.matmul(x, Wr) + br)
z = tf.sigmoid(tf.matmul(x, Wz) + bz)
h_ = tf.tanh(tf.matmul(x, Wx) + tf.matmul(previous_hidden_state, Wh) * r)
current_hidden_state = tf.mul((1 - z), h_) + tf.mul(previous_hidden_state, z)
return current_hidden_state
这里我明确地使用了权重Wx, Wr, Wz, Wh
和偏见br, bh, bz
等来获取更新的隐藏状态。这些权重和偏差是训练后学习/调整的。
如何利用 Tensorflow 的内置功能GRUCell
达到与上面相同的结果?