解決Tensorflow ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)

Choyang發表於2021-12-20

問題描述

在將一個陣列送入tensorflow訓練時,報錯如下:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)
陣列元素為陣列,每個陣列元素的shape不一致,示例如下:

cropImg[0].shape = (13, 13, 3)
cropImg[1].shape = (14, 13, 3)
cropImg[2].shape = (12, 13, 3)

環境

python 3.7.9
tensorflow 2.6.0
keras 2.6.0

解決方法

stackoverlow上有許多類似的報錯,大概意思都是資料型別錯誤,轉換的資料型別報錯中括號裡的資料型別,如:
Unsupported object type numpy.ndarray指cropImg陣列元素不是numpy.ndarray型別。
博主非常不解,嘗試了許多方法,都顯示cropImg陣列元素資料型別為numpy.ndarray,但錯誤一直存在。
後來突然轉念,在生成cropImg陣列時,有一個warning:

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  cropImg_ar = np.array(img_list)

cropImg陣列元素為shape不一致的陣列,這說明cropImg陣列元素型別實際上為object,會不會是tensorflow不接受object型別的資料導致的?
將cropImg陣列元素轉換為shape一致後,問題解決。

參考連結
https://stackoverflow.com/questions/62570936/valueerror-failed-to-convert-a-numpy-array-to-a-tensor-unsupported-object-type
https://stackoverflow.com/questions/58636087/tensorflow-valueerror-failed-to-convert-a-numpy-array-to-a-tensor-unsupporte
https://blog.csdn.net/liveshow021_jxb/article/details/112752145

相關文章