TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this t

weixin_43200354發表於2020-10-07

TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.

//錯誤資訊
TypeError                                 Traceback (most recent call last)
<ipython-input-11-f6a31a59ae6e> in <module>()
----> 1 loss3,RMSE_train1,MAE_train1,tv,train_pred_concat,RMSE_train_normalized,MAE_train1_normalized=train_lstm()
      2 #print('train_loss:',loss3)

<ipython-input-10-dba5b61ed852> in train_lstm(batch_size, time_step)
     83                 #訓練集的預測資料和真實資料
     84                 train_pred_concat=[]
---> 85                 train_pred_concat=train_predata(pred_train1)#有可能需要placeholder一下,看執行情況,標準化的訓練集預測資料
     86                 train_end=len(normalized_train_data)
     87                 train_y_normalized=normalized_train_data[0:train_end-1,3]

<ipython-input-8-f538bad668c6> in train_predata(pred_traindata, time_step)
     19     b=train_pred5[-1].T#取出最後一行,即編號為17495的那行
     20     train_pred_concat=tf.concat((train_pred6,b),axis=0)#湊出完整的預測資料(標準化版)
---> 21     pd.DataFrame(train_pred_concat).to_csv('E:\\TF_jupyter\\sht\\bishe_LSTM\\github-LSTM\\足球\\lstm_new\\new_SOC_Untitled14\\train_pred_concat.csv')
     22     #print('---return train_pred_concat---')
     23     return train_pred_concat

D:\anaconda3\envs\tensorflow\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
    500         elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
    501             if not isinstance(data, (abc.Sequence, ExtensionArray)):
--> 502                 data = list(data)
    503             if len(data) > 0:
    504                 if is_dataclass(data[0]):

D:\anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py in __iter__(self)
    475     if not context.executing_eagerly():
    476       raise TypeError(
--> 477           "Tensor objects are only iterable when eager execution is "
    478           "enabled. To iterate over this tensor use tf.map_fn.")
    479     shape = self._shape_tuple()

TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.

解決方法

sess=tf.InteractiveSession()
pd.DataFrame(train_pred_concat.eval()).to_csv('E:\\TF_jupyter\\sht\\bishe_LSTM\\github-LSTM\\足球\\lstm_new\\new_SOC_Untitled14\\train_pred_concat.csv')
分析

由錯誤資訊可以看出,錯誤的地方在pd.DataFrame(train_pred_concat).to_csv(‘E:\TF_jupyter\sht\bishe_LSTM\github-LSTM\足球\lstm_new\new_SOC_Untitled14\train_pred_concat.csv’)
這是因為train_pred_concat是Tensor變數,不能這樣直接儲存,需要.eval()一下才正確,注意括號不能省略,否則不起作用!!!!

歡迎批評指正

相關文章