5

Tensorflow의 코드 GRUCell에는 다음 숨겨진 상태가 시퀀스의 현재 입력과 함께 제공 될 때 업데이트 된 숨겨진 상태를 가져 오는 일반적인 작업이 표시됩니다.Tensorflow의 GRU 셀에 대한 설명?

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 

는하지만 어떤 weightsbiases 여기에 표시되지 않습니다. 예 : 내 이해는 ru을 얻으려면 가중치와 바이어스에 현재 입력 및/또는 숨겨진 상태를 곱하여 업데이트 된 숨겨진 상태를 가져와야합니다. 다음과 같이 내가 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을 어떻게 활용할 수 있습니까?

+0

그들은이'r'과 한 번에 모든 것을 할 수있는'z' 문을 연결, 계산을 절약 할 수 있습니다. –

답변

3

_linear 함수가 가중치와 바이어스를 추가하기 때문에 코드에 해당 코드가 표시되지 않습니다.

r, u = array_ops.split(1, 2, _linear([inputs, state], 
              2 * self._num_units, True, 1.0)) 

...

def _linear(args, output_size, bias, bias_start=0.0, scope=None): 
    """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. 

    Args: 
    args: a 2D Tensor or a list of 2D, batch x n, Tensors. 
    output_size: int, second dimension of W[i]. 
    bias: boolean, whether to add a bias term or not. 
    bias_start: starting value to initialize the bias; 0 by default. 
    scope: VariableScope for the created subgraph; defaults to "Linear". 

    Returns: 
    A 2D Tensor with shape [batch x output_size] equal to 
    sum_i(args[i] * W[i]), where W[i]s are newly created matrices. 

    Raises: 
    ValueError: if some of the arguments has unspecified or wrong shape. 
    """ 
    if args is None or (nest.is_sequence(args) and not args): 
    raise ValueError("`args` must be specified") 
    if not nest.is_sequence(args): 
    args = [args] 

    # Calculate the total size of arguments on dimension 1. 
    total_arg_size = 0 
    shapes = [a.get_shape().as_list() for a in args] 
    for shape in shapes: 
    if len(shape) != 2: 
     raise ValueError("Linear is expecting 2D arguments: %s" % str(shapes)) 
    if not shape[1]: 
     raise ValueError("Linear expects shape[1] of arguments: %s" % str(shapes)) 
    else: 
     total_arg_size += shape[1] 

    # Now the computation. 
    with vs.variable_scope(scope or "Linear"): 
    matrix = vs.get_variable("Matrix", [total_arg_size, output_size]) 
    if len(args) == 1: 
     res = math_ops.matmul(args[0], matrix) 
    else: 
     res = math_ops.matmul(array_ops.concat(1, args), matrix) 
    if not bias: 
     return res 
    bias_term = vs.get_variable(
     "Bias", [output_size], 
     initializer=init_ops.constant_initializer(bias_start)) 
    return res + bias_term 
+0

그래서 그것은 가중치와 편향이 요구에 따라 만들어지고 같은 변수 범위에서 호출 된 경우 동일한 것을 반환하는 get_variable을 사용하여 시간 단계에서 공유되는 것으로 보입니다. 가중치 행렬 그래도 초기화됩니다. –

+0

현재 변수 범위에 대한 기본 이니셜 라이저를 사용하여 초기화 된 것으로 생각합니다. – chasep255

+0

이것도 tensorflow 항목에 대한 내 다른 [질문] (http://stackoverflow.com/questions/39302344/tensorflow-rnn-input-size)에 대한 답변이라고 생각합니다. –