ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape
·
在使用np.asarray()或np.asanyarray()时报这个错,是因为要array化的对象“在第一维后具有不均匀的形状”,比如下面这样:
import numpy as np
li = [[1, 2], [3, 4, 5]]
arr = np.asarray(li)
# ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
有的numpy版本不报错而是警告:
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.
根据提示,加上 dtype=object 就不会再报错或警告:
import numpy as np
li = [[1, 2], [3, 4, 5]]
arr = np.asarray(li, dtype=object) # [list([1, 2]) list([3, 4, 5])]
解决。(如果本意需要转换的是均匀数据,就找找数据的问题)
我是在np.save()时遇到的这个情况,np.save()需要传入arr : array_like,我传入的是如上一个第一维后不均匀的list,在np.save()内部有arr = np.asanyarray(arr),为了不改变内置函数,可以选择在外部将list转为np.ndarray,再传入该np.ndarray,比如:
import numpy as np
path = './mydata.txt'
li = [[1, 2], [3, 4, 5]]
# np.save(path, li)
arr = np.asarray(li, dtype = object)
np.save(path, arr)
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)