You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建TensorFlow双向RNN触发TypeError错误,寻求修复方案

问题

尝试通过TensorFlow手绘图形分类教程训练循环神经网络,运行以下代码时:

def _add_regular_rnn_layers(convolved, lengths):
    """Adds RNN layers."""
    if params["cell_type"] == "lstm":
        cell = tf.compat.v1.nn.rnn_cell.BasicLSTMCell
    elif params["cell_type"] == "block_lstm":
        cell = tf.compat.v1.keras.layers.LSTMCell
    cells_fw = [cell(params["num_nodes"]) for _ in range(params["num_layers"])]
    cells_bw = [cell(params["num_nodes"]) for _ in range(params["num_layers"])]
    if params["dropout"] > 0.0:
        cells_fw = [tf.compat.v1.nn.rnn_cell.DropoutWrapper(cell) for cell in cells_fw]
        cells_bw = [tf.compat.v1.nn.rnn_cell.DropoutWrapper(cell) for cell in cells_bw]
    bidirectional_rnn = tf.keras.layers.Bidirectional(
        tf.keras.layers.RNN(cells_fw, return_sequences=True),
        merge_mode='concat',
        backward_layer=tf.keras.layers.RNN(cells_bw, return_sequences=True)
    )
    outputs = bidirectional_rnn(convolved)
    return outputs

在执行bidirectional_rnn = tf.keras.layers.Bidirectional(这一行时,出现错误:

TypeError: The argument 'cell' ({'class_name': 'BasicLSTMCell', 'config': {'name': 'basic_lstm_cell_1', 'trainable': True, 'dtype': None, 'num_units': 128, 'forget_bias': 1.0, 'state_is_tuple': True, 'activation': 'tanh', 'reuse': None}}) is not an RNNCell: 'output_size' property is missing, 'state_size' property is missing, either 'zero_state' or 'get_initial_state' method is required, is not callable.
修复建议
  • 统一API风格:代码混用了TensorFlow 1.x低阶RNN Cell和TensorFlow 2.x Keras RNN层,两者不兼容,需统一使用Keras原生组件:
    1. 改用Keras原生LSTM Cell适配tf.keras.layers.RNN:
      if params["cell_type"] == "lstm":
          cell = tf.keras.layers.LSTMCell
      elif params["cell_type"] == "block_lstm":
          cell = tf.keras.layers.LSTMCell  # Keras中无需区分普通LSTM和BlockLSTM,直接用LSTMCell即可
      
    2. 更简洁的方案是直接使用Keras完整LSTM层,无需手动构建Cell列表:
      def _add_regular_rnn_layers(convolved, lengths):
          """Adds RNN layers."""
          # 构建堆叠的LSTM层
          stacked_layers = []
          for _ in range(params["num_layers"]):
              lstm = tf.keras.layers.LSTM(
                  params["num_nodes"],
                  return_sequences=True,
                  dropout=params["dropout"] if params["dropout"] > 0 else 0
              )
              stacked_layers.append(lstm)
          
          # 双向RNN包装
          if params["num_layers"] > 1:
              rnn_cell = tf.keras.layers.StackedRNNCells(stacked_layers)
              bidirectional_rnn = tf.keras.layers.Bidirectional(
                  tf.keras.layers.RNN(rnn_cell, return_sequences=True),
                  merge_mode='concat'
              )
          else:
              bidirectional_rnn = tf.keras.layers.Bidirectional(
                  stacked_layers[0],
                  merge_mode='concat'
              )
          
          outputs = bidirectional_rnn(convolved)
          return outputs
      
  • 替换DropoutWrapper:TensorFlow 1.x的DropoutWrapper不适用于Keras Cell,直接使用Keras层自带的dropout参数即可实现正则化。
  • 多层RNN处理:若需堆叠多层RNN,用tf.keras.layers.StackedRNNCells包裹Cell列表后传入tf.keras.layers.RNN,或直接堆叠多个LSTM层再接入双向层。

内容的提问来源于stack exchange,提问作者Bobby Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:15:54