栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

踩坑历险记:can‘t convert np.ndarray of type numpy.object

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

踩坑历险记:can‘t convert np.ndarray of type numpy.object

文章目录
      • 问题记录
      • 解决方法
          • 方法一:蠢方法
          • 方法二:还可以的方法
      • 参考文献

问题记录

我有一个numpy.ndarray类型的数组,数组里面的数据是tensor类型,现在我想将这个数组转化为tensor类型,然后报错了,代码和报错截图如下:
代码及代码运行截图:

import numpy as np
import torch

a = torch.tensor([1, 1, 1])
b = torch.tensor([2, 2, 2])
c = np.array([a, b])
print("print the c: n {}n".format(c))
print("c's type is {}".format(type(c)))

d = torch.tensor(c)
print("print the d: n {}n".format(d))
print("d's type is {}".format(type(d)))


报错截图:

错误原因解释:就是numpy数据类型里只有float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, bool,没有tensor类型,所以出错了。一般而言,只要对数组里的数据进行强制转换,转换为float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, bool中的任意一种都行,可以参考这篇文章 异常can’t convert np.ndarray of type numpy.object_.。但不适用我们这次的问题。

解决方法

如果有大神晓得其他方法,并且能在评论区告诉我的话,那就真的感激不尽啦!

方法一:蠢方法

用了蠢方法,先遍历将numpy.ndarray数组里的元素全部转换为numpy.ndarray类型,也就是我将数组里的tensor类型数据转换为了numpy.ndarray类型,然后再使用torch.tensor命令进行转换,嗯,然后就成功了。
代码及代码运行截图:

import numpy as np
import torch

a = torch.tensor([1, 1, 1])
b = torch.tensor([2, 2, 2])
c = np.array([a, b])
print("print the c: n {}n".format(c))
print("c's type is {}".format(type(c)))

c = [val.numpy() for val in c]  #  改动在这里,将tensor转换为了numpy
d = torch.tensor(c)
print("print the d: n {}n".format(d))
print("d's type is {}".format(type(d)))

方法二:还可以的方法

先将numpy.ndarray数组转换为list类型,再使用torch.stack命令进行转换,嗯,然后也成功了。
代码及代码运行截图:

import numpy as np
import torch

a = torch.tensor([1, 1, 1])
b = torch.tensor([2, 2, 2])
c = np.array([a, b])
print("print the c: n {}n".format(c))
print("c's type is {}".format(type(c)))

d = torch.stack(list(c))   # 在这里改动了
print("print the d: n {}n".format(d))
print("d's type is {}".format(type(d)))

参考文献
  1. 异常can’t convert np.ndarray of type numpy.object_.
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/840463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号