【d2l】2.2.数据预处理
【d2l】2.2.数据预处理
本节主要涉及pandas的应用
但是由于我的torch版本较高,因而只能采用高版本torch,有些细节需要加以调整
读取数据集
首先用os库生成一个csv
import os
os.makedirs(os.path.join('.', 'data'), exist_ok = True)
data_file = os.path.join('.', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
f.write('NumRooms,Alley,Price\n');
f.write('NA,Pave,127500\n')
f.write('2,NA,106000\n')
f.write('4,NA,178100\n')
f.write('NA,NA,140000\n')
然后用pandas读取
import pandas as pd
data = pd.read_csv(data_file)
print(data)
NumRooms Alley Price
0 NaN Pave 127500
1 2.0 NaN 106000
2 4.0 NaN 178100
3 NaN NaN 140000
处理缺失值
对于数据的缺失,采用fillna函数即可,但需要注意标明只考虑数字列,这与老版本不一样
inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = inputs.fillna(inputs.mean(numeric_only = True))
print(inputs)
NumRooms Alley
0 3.0 Pave
1 2.0 NaN
2 4.0 NaN
3 3.0 NaN
接着对于类别值或是离散值,采用get_dummies函数来转化,分为不同类别的列
inputs = pd.get_dummies(inputs, dummy_na = True)
print(inputs)
NumRooms Alley_Pave Alley_nan
0 3.0 True False
1 2.0 False True
2 4.0 False True
3 3.0 False True
转化为张量格式
可以发现前面get_dummies之后得到的是bool类型,需要转化成numpy之后强制转换一下类型
import torch
X = torch.tensor(inputs.to_numpy(dtype = float))
y = torch.tensor(outputs.to_numpy(dtype = float))
X, y
(tensor([[3., 1., 0.],
[2., 0., 1.],
[4., 0., 1.],
[3., 0., 1.]], dtype=torch.float64),
tensor([127500., 106000., 178100., 140000.], dtype=torch.float64))
以上是最基础的操作

浙公网安备 33010602011771号