动手学机器学习v2-04-2数据预处理

数据预处理

1 读取数据集

  • 判断路径下是否有data命名的文件夹,没有的话,创建文件house_tiny.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,只需取消对以下行的注释:
# !pip install pandas
import pandas as pd

data = pd.read_csv(data_file)
print(data)

2 处理缺失值

  • 通过位置索引iloc,我们将data分成inputs和outputs,其中前者为data的前两列,而后者为data的最后一列。对于inputs中缺少的数值,我们用同一列的均值替换“NaN”项
inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = inputs.fillna(inputs.mean())
print(inputs)

  • 对于inputs中的类别值或离散值,我们将“NaN”视为一个类别。由于“巷子”(“Alley”)列只接受两种类型的类别值“Pave”和“NaN”,pandas可以自动将此列转换为两列“Alley_Pave”和“Alley_nan”

有值的置为1,没有值的置为0

inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)

3 转换为张量格式

import torch

X, y = torch.tensor(inputs.values), torch.tensor(outputs.values)
X, y

4 小结

  • pandas可以与张量兼容。
  • 插值和删除可用于处理缺失的数据
    • nputs.isnull().sum() 返回每一列缺失值得个数。
    • inputs.isnull().sum().idxmax() 得到缺失值最多的那一列的索引值。
    • 把缺失值最多的那一列删除
      Max_Nan_Num=inputs.isnull().sum().idxmax()
      inputs=inputs.drop(Max_Nan_Num,axis=1)
posted @ 2021-10-03 11:15  Trouvaille_fighting  阅读(98)  评论(0编辑  收藏  举报