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


問題描述

在將一個數組送入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

解決方法

stackoverflow上有許多類似的報錯,大概意思都是數據類型錯誤,轉換的數據類型報錯中括號里的數據類型,如:
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM