在使用numpy库中的numpy.asarray(), numpy.array() ... 等类似把tuple数据类型转化为array的形式时,遇到了“value error: only one element tensors can be converted to python scalars”的错误。错误的大致意思是:只有单元素的张量可以被转化成python的尺度数。
例如:
tp1 = (1,2,3,4,5,6)
tp2 = (2,2,3,4,5,6)
arr1 = np.array(tp1,dtype=float)
arr2 = np.array(tp2,dtype=float)
print(type(arr1)) #查看arr1的数据类型 print(d)
返回 <class 'numpy.ndarray'>
遇到这样的:
tp = (tensor([[1,2,3],[4,5,6]]))
就不能直接使用numpy.array()函数进行数据类型的转换。
# tuple _ list
listtuple1 = []
for i in range(len(tp)):
listtuple1 += list(tp[i].view(-1))
# list _ tensor
tlisttuple1 = torch.tensor(listtuple1)
# tensor _ array
ar = numpy.asarray(tlisttuple1)
或者 你想要的array的形状:ar = numpy.asarray(tlisttuple1).reshape(x,y)