简体   繁体   English

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

[英]TypeError: can't convert np.ndarray of type numpy.object_

How to convert a numpy array of dtype=object to torch Tensor ?如何将dtype=object的 numpy 数组转换为 torch Tensor

array([
   array([0.5, 1.0, 2.0], dtype=float16),
   array([4.0, 6.0, 8.0], dtype=float16)
], dtype=object)

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.从您的错误消息中,我可以看到您尝试将包含对象的 numpy 数组转换为火炬张量。 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.5, 1.0, 2.0], dtype=np.float16),
    np.array([4.0, 6.0, 8.0], dtype=np.float16),
])

b = torch.from_numpy(a)

print(a.dtype) # This should not be 'object'
print(b)

Output输出

float16
tensor([[0.5000, 1.0000, 2.0000],
        [4.0000, 6.0000, 8.0000]], dtype=torch.float16)

Just adding to what was written above-只需添加上面写的内容-

First you should make sure your array dtype ins't a 'O' (Object).首先,您应该确保您的数组 dtype 不是“O”(对象)。

You do that by: ( credit )你这样做:( 信用

a=np.vstack(a).astype(np.float)

Then you can use:然后你可以使用:

b = torch.from_numpy(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM