【问题标题】:How to print out values of LSTM gates in TensorFlow?如何在 TensorFlow 中打印出 LSTM 门的值?
【发布时间】:2017-10-08 14:31:39
【问题描述】:

我将 TensorFlow LSTM 用于语言模型(我有一个单词序列并想预测下一个单词),并且在运行语言模型时,我想打印出忘记的值,每一步的输入,变换和输出门。我该怎么做?

通过检查https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/rnn_cell.py 中的代码,我看到LayerNormBasicLSTMCell 类有一个call 方法,其中包含我要打印出来的i, j, f, o 变量。

  def call(self, inputs, state):
    """LSTM cell with layer normalization and recurrent dropout."""
    c, h = state
    args = array_ops.concat([inputs, h], 1)
    concat = self._linear(args)

    i, j, f, o = array_ops.split(value=concat, num_or_size_splits=4, axis=1)
    if self._layer_norm:
      i = self._norm(i, "input")
      j = self._norm(j, "transform")
      f = self._norm(f, "forget")
      o = self._norm(o, "output")

    g = self._activation(j)
    if (not isinstance(self._keep_prob, float)) or self._keep_prob < 1:
      g = nn_ops.dropout(g, self._keep_prob, seed=self._seed)

    new_c = (c * math_ops.sigmoid(f + self._forget_bias)
             + math_ops.sigmoid(i) * g)
    if self._layer_norm:
      new_c = self._norm(new_c, "state")
    new_h = self._activation(new_c) * math_ops.sigmoid(o)

    new_state = core_rnn_cell.LSTMStateTuple(new_c, new_h)
    return new_h, new_state

但是,有没有一种简单的方法可以打印出这些变量?或者我是否必须在运行 LTSM 的脚本中重新创建此方法中的相关代码行?

【问题讨论】:

    标签: python tensorflow lstm


    【解决方案1】:

    基本上你可以这样做:

    首先返回你需要的状态,例如return new_h, new_state, i, j, f, o。要进行此类更改,您应该从 TensorFlow 复制源代码文件并将其像您自己的代码一样导入到您的代码中。
    然后在您的代码中,在session.run(to_return, feed_dict) 中,使to_return 像这样:

    output, state, i, j, f, o = lstm_cell(input, state)   
    to_return = {
        "new_h": output, 
        "new_state": state,
        "i": i,
        "j": j,
        "f": f, 
        "o": o,
    }
    
    results = session.run(to_return, feed_dict) # get what you want from the 
    # graph(which are tensors), resulting in results of a dictionary with values
    # being numpy arrays. 
    
    print results["i"] # you'll get a numpy array representing the i gate     
    

    【讨论】:

    • 这是我在尝试您的解决方案后得到的错误:文件“rnn.py”,第 1327 行,在 static_rnn state_size=cell.state_size) 文件“rnn.py”,第 263 行,在 _rnn_step _maybe_copy_some_through ) 文件“deprecation.py”,第 454 行,在 new_func 返回 func(*args, **kwargs) 文件“control_flow_ops.py”,第 2057 行,在 cond orig_res_f,res_f = context_f.BuildCondBranch(false_fn) 文件“control_flow_ops.py ",第 1895 行,在 BuildCondBranch original_result = fn() 文件中 "rnn.py",第 233 行,在 _maybe_copy_some_through new_output,new_state = call_cell() ValueError: too many values to unpack (expected 2
    【解决方案2】:

    我曾经在 git issue 中问过类似的问题。响应是原始单元格只返回ch(这也是每一步的输出y)。如果要获取内部变量,需要自己动手。

    这里是链接:https://github.com/tensorflow/tensorflow/issues/5731

    【讨论】:

    • 你能做到吗?我还需要记录所有 LSTM 单元门。但是,我更改了调用的输出,它破坏了太多东西。你有什么例子吗?
    猜你喜欢
    • 2017-01-03
    • 2020-06-05
    • 2021-10-21
    • 2016-09-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多