运行LSTM模型遇AttributeError:keras.layers无LSTMStateTuple属性
解决TensorFlow中LSTMStateTuple属性不存在的问题
错误信息
AttributeError: module 'keras.api._v2.keras.layers' has no attribute 'LSTMStateTuple'
问题代码
# Create cell state and hidden state variables to maintain the state of the LSTM c, h = [], [] initial_state = [] for li in range(n_layers): c.append(tf.Variable(tf.zeros([batch_size, num_nodes[li]]), trainable=False)) h.append(tf.Variable(tf.zeros([batch_size, num_nodes[li]]), trainable=False)) initial_state.append(tf.keras.layers.LSTMStateTuple(c[li], h[li])) # Do several tensor transformations, because the function dynamic_rnn requires the output to be of # a specific format. Read more at: https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn all_inputs = tf.concat([tf.expand_dims(t, 0) for t in train_inputs], axis=0) # Create LSTM layer lstm_layer = tf.keras.layers.LSTM(num_nodes[-1], return_sequences=True, return_state=True, dropout=dropout) # Pass inputs and initial state to the LSTM layer all_lstm_outputs, final_state, _ = lstm_layer(all_inputs, initial_state=initial_state) all_outputs = tf.keras.layers.Dense(1)(all_lstm_outputs) split_outputs = tf.split(all_outputs, num_unrollings, axis=0)
解决方案
原因
LSTMStateTuple不属于tf.keras.layers模块,它是TensorFlow 1.x旧版RNN API的组件。在TensorFlow 2.x的原生Keras API中,LSTM层接受的初始状态可以直接用**(细胞状态c, 隐藏状态h)**的普通元组表示,无需依赖专门的LSTMStateTuple类。
修复代码
修改初始化状态的循环部分,用普通元组替代LSTMStateTuple:
# Create cell state and hidden state variables to maintain the state of the LSTM c, h = [], [] initial_state = [] for li in range(n_layers): c.append(tf.Variable(tf.zeros([batch_size, num_nodes[li]]), trainable=False)) h.append(tf.Variable(tf.zeros([batch_size, num_nodes[li]]), trainable=False)) # 直接使用元组传递状态,替代LSTMStateTuple initial_state.append((c[li], h[li]))
备选方案(兼容旧代码)
如果需要保留LSTMStateTuple的写法,可以导入正确的兼容模块:
from tensorflow.compat.v1.nn.rnn_cell import LSTMStateTuple
但更推荐使用普通元组的方式,适配TF2.x的原生Keras API。
内容的提问来源于stack exchange,提问作者Swapnil kumar Sahu
相关产品推荐
相关产品推荐

