TypeError:无法转换numpy.object_类型的np.ndarray

时间:2019-04-17 09:19:46

标签: numpy pytorch

如何将numpy ndarry转换为火炬张量?

这是我的数据:

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)

1 个答案:

答案 0 :(得分:0)

很难正确回答,因为您没有向我们展示如何尝试做到这一点。从错误消息中,我可以看到您尝试将包含对象的numpy数组转换为割炬张量。这不起作用,您将需要一个数字数据类型:

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)