本文介绍了类型错误:无法转换 numpy.object_ 类型的 np.ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 numpy ndarry 转换为火炬张量?
How to convert a numpy ndarry to torch tensor?
这是我的数据:
array([array([-0.4287 , -1.193 , -2.156 , -0.2264 , -1.978 , -1.101 , -3.395 , 0.2974 ], dtype=float16),
array([-0.3386 , 1.398 , -1.083 , 0.2961 , -0.7354 , -1.326 , -4.33 , 0.6284 ], dtype=float16)],
dtype=object)
推荐答案
很难正确回答,因为您没有向我们展示您如何尝试去做.从您的错误消息中,我可以看到您尝试将包含对象的 numpy 数组转换为火炬张量.这不起作用,您将需要数字数据类型:
It is difficult to answer properly since you do not show us how you try to do it. From your error message I can see that you try to convert a numpy array containing objects to a torch tensor. This does not work, you will need a numeric data type:
import torch
import numpy as np
# Your test array without 'dtype=object'
a = np.array([
np.array([-0.4287 , -1.193 , -2.156 , -0.2264 , -1.978 , -1.101 , -3.395 , 0.2974 ], dtype=np.float16),
np.array([-0.3386 , 1.398 , -1.083 , 0.2961 , -0.7354 , -1.326 , -4.33 , 0.6284 ], dtype=np.float16)
])
print(a.dtype) # This should not be 'object'
b = torch.from_numpy(a)
print(b)
输出
float16
tensor([[-0.4287, -1.1934, -2.1562, -0.2264, -1.9775, -1.1006, -3.3945, 0.2974],
[-0.3386, 1.3984, -1.0830, 0.2961, -0.7354, -1.3262, -4.3281, 0.6284]],
dtype=torch.float16)
这篇关于类型错误:无法转换 numpy.object_ 类型的 np.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!