运行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.
报错信息如下:
通过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)