【问题标题】:Tensorflow: Replacement for tf.nn.rnn_cell._linear(input, size, 0, scope)Tensorflow:替换 tf.nn.rnn_cell._linear(input, size, 0, scope)
【发布时间】:2017-02-24 11:08:11
【问题描述】:

我正在尝试让来自https://arxiv.org/pdf/1609.05473.pdf 的 SequenceGAN (https://github.com/LantaoYu/SeqGAN) 运行。
在修复了明显的错误后,比如用stack替换pack,它仍然没有运行,因为高速公路网络部分需要tf.nn.rnn_cell._linear函数:

# highway layer that borrowed from https://github.com/carpedm20/lstm-char-cnn-tensorflow
def highway(input_, size, layer_size=1, bias=-2, f=tf.nn.relu):
    """Highway Network (cf. http://arxiv.org/abs/1505.00387).

    t = sigmoid(Wy + b)
    z = t * g(Wy + b) + (1 - t) * y
    where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
    """
    output = input_
    for idx in range(layer_size):
        output = f(tf.nn.rnn_cell._linear(output, size, 0, scope='output_lin_%d' % idx)) #tf.contrib.layers.linear instad doesn't work either.
        transform_gate = tf.sigmoid(tf.nn.rnn_cell._linear(input_, size, 0, scope='transform_lin_%d' % idx) + bias)
        carry_gate = 1. - transform_gate

        output = transform_gate * output + carry_gate * input_

    return output

tf.nn.rnn_cell._linear 函数在 Tensorflow 1.0 或 0.12 中似乎不再存在,我不知道用什么替换它。我找不到任何新的实现,或者关于 tensorflow 的 github 或(不幸的是非常稀疏的)文档的任何信息。

有人知道这个功能的新挂件吗? 提前非常感谢!

【问题讨论】:

  • 为什么 tf.contrib.layers.linear 不适合你?
  • tf1.8中还包含这个函数吗?

标签: python tensorflow neural-network


【解决方案1】:

我在使用 SkFlow 的 TensorFlowDNNRegressor 时遇到了这个错误。 第一次看到ruoho ruots的回答,有点懵。 但第二天我明白了他的意思。

这是我的工作:

from tensorflow.python.ops import rnn_cell_impl

tf.nn.rnn_cell._linear 替换为rnn_cell_impl._linear

【讨论】:

    【解决方案2】:

    ruoho ruotsi 的答案几乎是正确的: 然而,linear定义并不位于tf.contrib.rnn.basicRNNCell,而是分别位于tf.contrib.rnn.python.ops.rnn_celltf.contrib.rnn.python.ops.core_rnn_cell_impl

    你可以找到他们的源代码herehere

    【讨论】:

    • 1.2 版中没有
    • 这仅对 1.0 和 1.1 版本有效。他们(当时)说他们会在以后的版本中将这些功能移动到其他地方,这可能是 1.2 中发生的事情
    【解决方案3】:

    在 1.0 版中,一切都发生了变化。我有类似的狩猎更新 tf.nn.rnn_cell.LSTMCelltf.contrib.rnn.BasicLSTMCell

    对于您的情况,tf.nn.rnn_cell._linear 现在位于tf.contrib.rnn.python.ops.core_rnn_cell_impl 以及BasicRNNCell 的定义中。检查BasicRNNCell docssource code,我们在L113-L118 看到_linear 的使用。

      def __call__(self, inputs, state, scope=None):
        """Most basic RNN: output = new_state = act(W * input + U * state + B)."""
        with _checked_scope(self, scope or "basic_rnn_cell", reuse=self._reuse):
          output = self._activation(
              _linear([inputs, state], self._num_units, True))
        return output, output
    

    _linear 方法在line 854 定义为:
    Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.

    祝你好运!

    【讨论】:

    • 我在 v 1.0 上尝试了这个解决方案,但得到了AttributeError: type object 'BasicRNNCell' has no attribute '_linear'
    • 其实是在另一个文件中定义的。请参阅我的答案以获取正确的代码位置。
    • 我引用了tf.contrib.rnn.python.ops.core_rnn_cell_impl,但你是对的,我不清楚BasicRNNCelllinear 都存在于这个文件中。 github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/… 好收获。我会更新我的答案。
    【解决方案4】:

    为了解决这个问题,我们可以定义一个linear()函数。

    def linear(input_, output_size, scope=None):
        '''
        Linear map: output[k] = sum_i(Matrix[k, i] * args[i] ) + Bias[k]
        Args:
            args: a tensor or a list of 2D, batch x n, Tensors.
        output_size: int, second dimension of W[i].
        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.
        '''
    
        shape = input_.get_shape().as_list()
        if len(shape) != 2:
            raise ValueError("Linear is expecting 2D arguments: %s" % str(shape))
        if not shape[1]:
            raise ValueError("Linear expects shape[1] of arguments: %s" % str(shape))
        input_size = shape[1]
    
        # Now the computation.
        with tf.variable_scope(scope or "SimpleLinear"):
            matrix = tf.get_variable("Matrix", [output_size, input_size], dtype=input_.dtype)
            bias_term = tf.get_variable("Bias", [output_size], dtype=input_.dtype)
    
        return tf.matmul(input_, tf.transpose(matrix)) + bias_term
    
    
    def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
        """Highway Network (cf. http://arxiv.org/abs/1505.00387).
        t = sigmoid(Wy + b)
        z = t * g(Wy + b) + (1 - t) * y
        where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
        """
    
        with tf.variable_scope(scope):
            for idx in range(num_layers):
                g = f(linear(input_, size, scope='highway_lin_%d' % idx))
    
                t = tf.sigmoid(linear(input_, size, scope='highway_gate_%d' % idx) + bias)
    
                output = t * g + (1. - t) * input_
                input_ = output
    
        return output
    

    https://github.com/mkroutikov/tf-lstm-char-cnn/blob/7e899e6992cbf9a96e6d791e5d364eaaeec339a2/model.py

    【讨论】:

      【解决方案5】:

      tensorflow.python.ops.rnn_cell_impl._linear 现在位于 tensorflow.contrib.rnn.python.ops.core_rnn_cell._linear。而且我更喜欢用 tf.layers.Dense 来代替。 例如,改变

      from tensorflow.contrib.rnn.python.ops import core_rnn_cell
      core_rnn_cell._linear(states, length, bias=True)
      

      tf.layers.Dense(units=length)(states)
      

      我使用的是 tensorflow 1.6。

      【讨论】:

        【解决方案6】:

        现在当你使用_linear函数时,请这样使用:

        from tensorflow.contrib.rnn.python.ops import core_rnn_cell

        core_rnn_cell._linear(output, size)
        

        这里是其对应源文件的链接。 source file

        这是因为在tf r1.5之后,这个函数的位置发生了变化。

        当你使用tf r1.4甚至更老的版本时,请这样使用:

        from tensorflow.python.ops import rnn_cell_impl
        
        rnn_cell_impl._linear(output, size)
        

        这里是旧版_linear 的链接。 source file

        至于tf.nn.rnn_cell._linear,这个功能早就没有了。

        【讨论】:

        • 对于 tensorflow 1.15 版,这对我有用!
        【解决方案7】:

        至于现在(1.2r0),您可以将其替换为 tf.contrib.layers.fully_connected(inputs=[inputs, state], num_outputs=self._num_units, biases_initializer=tf.constant_initializer(0.0), activation_fn=None) 请注意,biases_initializer 对于 _linear 默认为全零,对于 fully_connected 则完全没有偏差。

        【讨论】:

          【解决方案8】:

          使用rnn_cell.LayerNormBasicLSTMCell._linear 而不是_linear

          【讨论】:

            猜你喜欢
            • 2017-07-08
            • 2018-08-01
            • 1970-01-01
            • 2021-03-28
            • 1970-01-01
            • 2016-03-13
            • 1970-01-01
            • 2019-12-10
            • 2019-12-06
            相关资源
            最近更新 更多