使用TensorFlow拼接RNN单元时遇AttributeError: Tensor对象无'c'属性
解决AttributeError: 'Tensor' object has no attribute 'c'的问题
你在使用TensorFlow双向LSTM时碰到了一个典型的参数配置问题,我来帮你拆解原因和解决办法:
错误根源分析
你在定义LSTMCell时设置了state_is_tuple=False,这个参数会让LSTM的状态输出变成一个拼接后的单一Tensor,而非默认的LSTMStateTuple(这个元组自带c(细胞状态)和h(隐藏状态)两个可访问属性)。所以当你尝试调用fw_st.c或bw_st.c时,自然会报错——此时fw_st是纯Tensor,根本没有c这个属性。
两种可行解决方案
方案1:使用默认的state_is_tuple=True(推荐)
TensorFlow官方更推荐这种模式,后续版本也逐步淘汰了state_is_tuple=False的支持。只需调整LSTMCell的初始化参数,就能正常通过.c和.h访问状态:
def _add_encoder(self, encoder_inputs, seq_len): with tf.variable_scope('encoder'): # 移除state_is_tuple=False,或显式设置为True(默认值就是True) cell_fw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init, state_is_tuple=True) cell_bw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init, state_is_tuple=True) (encoder_outputs, (fw_st, bw_st)) = tf.nn.bidirectional_dynamic_rnn( cell_fw, cell_bw, encoder_inputs, sequence_length=seq_len, dtype=tf.float32) # 现在可以正常访问c属性了 fw_cell_state = fw_st.c bw_cell_state = bw_st.c # 后续业务逻辑...
方案2:若必须保留state_is_tuple=False,手动拆分张量
如果你因特定需求必须使用拼接状态的模式,需要自行把合并后的Tensor拆分成细胞状态和隐藏状态。由于状态是c和h拼接而成,总长度为2*hidden_dim,可以按维度拆分:
def _add_encoder(self, encoder_inputs, seq_len): with tf.variable_scope('encoder'): cell_fw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init, state_is_tuple=False) cell_bw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init, state_is_tuple=False) (encoder_outputs, (fw_st, bw_st)) = tf.nn.bidirectional_dynamic_rnn( cell_fw, cell_bw, encoder_inputs, sequence_length=seq_len, dtype=tf.float32) # 手动拆分状态张量:前半段是细胞状态c,后半段是隐藏状态h hidden_dim = self._hps.hidden_dim.value fw_cell_state = fw_st[:, :hidden_dim] fw_hidden_state = fw_st[:, hidden_dim:] bw_cell_state = bw_st[:, :hidden_dim] bw_hidden_state = bw_st[:, hidden_dim:] # 后续业务逻辑...
额外提示
注意tf.contrib.rnn模块在TensorFlow 2.x中已被迁移到tf.keras.layers或tf.nn.rnn_cell下,如果你使用的是新版本TF,建议改用tf.keras.layers.LSTMCell,用法类似且更稳定。
内容的提问来源于stack exchange,提问作者K.cyrine
相关产品推荐
相关产品推荐

