Pytorch学习日记:can‘t convert np.ndarray of type numpy.object_

运行torch.tensor报错can’t convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

报错信息如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/831497808bee4cac8ad14b0309f
通过features.info() 发现数据类型有object
推测由于读入的numpy数组里的元素是object类型,无法将这种类型转换成tensor

features = features.astype(float)  # 强制类型转换示例

类型转换后,还是报错,使用info方法查看类型

print(features.info())
'''
Data columns (total 13 columns):
 #   Column                      Non-Null Count  Dtype  
---  ------                      --------------  -----  
 0   Age                         891 non-null    float64
 1   SibSp                       891 non-null    int64  
 2   Parch                       891 non-null    int64  
 3   Fare                        891 non-null    float64
 4   Pclass_1                    891 non-null    bool   
 5   Pclass_2                    891 non-null    bool   
 6   Pclass_3                    891 non-null    bool   
 7   Sex_female                  891 non-null    bool   
 8   Sex_male                    891 non-null    bool   
 9   Embarked_29.69911764705882  891 non-null    bool   
 10  Embarked_C                  891 non-null    bool   
 11  Embarked_Q                  891 non-null    bool   
 12  Embarked_S                  891 non-null    bool   
dtypes: bool(9), float64(2), int64(2)
'''

在网上查找相关错误后,发现如下信息:
TypeError: can’t convert np.ndarray of type numpy.bool_.,这个是因为不能将bool类型的转化,表明了np.bool和tensor之间是不能直接转化的。

写的代码中,多个列数据类型bool值,因此为了转化为tensor的uint8类型。

features[['列名']] = features[['列名']].astype('uint8')

执行下面的代码,发现不会再报错,且成功转化为tensor

X= torch.from_numpy(features.values)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值