ShusenTang / Dive-into-DL-PyTorch

本项目将《动手学深度学习》(Dive into Deep Learning)原书中的MXNet实现改为PyTorch实现。
http://tangshusen.me/Dive-into-DL-PyTorch
Apache License 2.0
18.07k stars 5.37k forks source link

3.16 实战Kaggle比赛:房价预测 np转成tensor会报错问题 #187

Closed Mr47121836 closed 1 year ago

Mr47121836 commented 1 year ago

bug描述 image

版本信息 pytorch:1.8.0+cu111 torchvision:0.9.1+cu101 torchtext:0.9.0 ...

awei-lwj commented 1 year ago

可能时间有点久了,这里提供一下bug的修复方法 Debug:

这里书上的代码:

n_train = train_data.shape[0]
train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float)
test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float)
train_labels = torch.tensor(train_data.SalePrice.values, dtype=torch.float).view(-1, 1)

会出现bug: 3 B9

原因以及Debug的方法 https://discuss.pytorch.org/t/creating-tensor-typeerror-cant-convert-np-ndarray-of-type-numpy-object/125741

3 C0

You won’t be able to directly convert it as the object type contains arbitrary or mixed data. Transform your numpy object to an array first and call torch.from_numpy afterwards.

也就是改成像我这样,先变成numpyarray然后强制类型转化,然后在直接转为tensor


train_features = np.array(all_features[:n_train]).astype(np.float64)
train_features = torch.from_numpy(train_features)

test_features  = np.array(all_features[n_train:].values).astype(np.float64)
test_feature
Mr47121836 commented 1 year ago

这是来自QQ邮箱的假期自动回复邮件。你好,我最近正在休假中,无法亲自回复你的邮件。我将在假期结束后,尽快给你回复。

awei-lwj commented 1 year ago

train_features = np.array(all_features[:n_train]).astype(np.float64) train_features = torch.from_numpy(train_features)

test_features = np.array(all_features[n_train:].values).astype(np.float64) test_features = torch.from_numpy(test_features)

Mr47121836 commented 1 year ago

谢谢