机器学习中数据清洗&预处理

数据预处理是建立机器学习模型的第一步,对最终结果有决定性的作用:如果你的数据集没有完成数据清洗和预处理,那么你的模型很可能也不会有效

第一步,导入数据

进行学习的第一步,我们需要将数据导入程序以进行下一步处理

加载 nii 文件并转为 numpy 数组

import nibabel as nib
from skimage import transform
import os
import numpy as np

img = nib.load(img_file)  
img = img.get_fdata()  
img = transform.resize(img[:, :, :, 0], (256, 256, 5))  
img = np.squeeze(img)  
train_img[i - 1, :, :, :] = img[:, :, :]  

第二步,数据预处理

Python提供了多种多样的库来完成数据处理的的工作,最流行的三个基础的库有:<b>Numpy</b>、<b>Matplotlib</b> 和 <b>Pandas</b>。Numpy 是满足所有数学运算所需要的库,由于代码是基于数学公式运行的,因此就会使用到它。Maplotlib(具体而言,Matplotlib.pyplot)则是满足绘图所需要的库。Pandas 则是最好的导入并处理数据集的一个库。对于数据预处理而言,Pandas 和 Numpy 基本是必需的

在导入库时,如果库名较长,最好能赋予其缩写形式,以便在之后的使用中可以使用简写。如

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

导入数据

import pandas as pd

def read_data(file_name : str):
    suffix = file_name.split('.')
    if suffix[1] == "csv":
        dataset = pd.read_csv(file_name)
        return dataset
    return None

读取的数据为

animal age worth friendly
0 cat 3 1200.0 yes
1 dog 4 2400.0 yes
2 dog 3 7000.0 no
3 cat 2 3400.0 yes
4 moose 6 4000.0 no
5 moose 3 NaN yes

将数据划分为因变量和自变量(y = f(x))

dataset = read_data("data.csv")  # pandas.core.frame.DataFrame
print(dataset)
x = dataset.iloc[:, :-1].values  # 将Dataframe转为数组,且不包括最后一列
y = dataset.iloc[:, 3].values  # dataset最后一列

x = \begin{bmatrix} {'cat'} & {3} & {1200.0} \\ {'dog'} & {4} & {2400.0} \\ {'dog'} & {3} & {7000.0} \\ {'cat'} & {2} & {3400.0} \\ {'moose'} & {6} & {4000.0} \\ {'moose'} & {3} & {nan} \end{bmatrix} \\ y = ['yes', 'yes', 'no', 'yes', 'no', 'yes']

可见 x 中是有一项数据是缺失的,此时可以使用 <b>scikit-learn</b> 预处理模型中的 <b>imputer</b> 类来填充缺失项

from sklearn.preprocessing import Imputer

imputer = Imputer(missing_values = np.nan, strategy = 'mean', axis = 0) # 使用均值填充缺失数据
imputer = imputer.fit(x[:, 1:3])
x[:, 1:3] = imputer.transform(x[:, 1:3])

其中 missing_values 指定了待填充的缺失项值, strategy 指定填充策略,此处填充策略使用的是均值填充,也可以使用中值,众数等策略

填充结果

\begin{bmatrix} {'cat'} & {3} & {1200.0} \\ {'dog'} & {4} & {2400.0} \\ {'dog'} & {3} & {7000.0} \\ {'cat'} & {2} & {3400.0} \\ {'moose'} & {6} & {4000.0} \\ {'moose'} & {3} & {3600.0} \\ \end{bmatrix}

这种填充适用于数字的填充,如果是属性填充,我们可以将属性数据编码为数值。此时我们可以使用 <b>sklearn.preprocessing</b> 所提供的 <b>LabelEncoder</b> 类

from sklearn.preprocessing import LabelEncoder

print(y)
labelencoder = LabelEncoder()
y = labelencoder.fit_transform(y)
print(y)

编码结果
y = ['yes', 'yes', 'no', 'yes', 'no', 'yes'] \\ \Downarrow \\ y = [1, 1, 0, 1, 0, 1]

训练集与测试集的划分

此时我们可以使用 sklearn.model_selection.train_test_split 来进行划分

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

进行测试集与训练集划分的一种常见的方法是将数据集按 80/20 进行划分,其中 80% 的数据用作训练,20% 的数据用作测试,由 test_size = 0.2 指明,random_state 指定是否随机划分

特征缩放

当我们的数据跨度很大的话或者在某些情况下(如:学习时,模型可能会因数据的大小而给予不同的权重,而我们并不需要如此的情况),我们可以将数据特征进行缩放,使用 sklearn.preprocessing.StandardScaler

from sklearn.preprocessing import StandardScaler

x[:, 0] = labelencoder.fit_transform(x[:, 0]) # 将属性变为数字
print(x_train)
sc_x = StandardScaler() #
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)
print(x_train)

结果

\begin{bmatrix} {1} & {4.0} & {2400.0} \\ {0} & {2.0} & {3400.0} \\ {0} & {3.0} & {1200.0} \\ {2} & {6.0} & {4000.0} \end{bmatrix}
\Downarrow
\begin{bmatrix} {0.30151134} & {0.16903085} & {-0.32961713} \\ {-0.90453403} & {-1.18321596} & {0.61214609} \\ {-0.90453403} & {-0.50709255} & {-1.45973299} \\ {1.50755672} & {1.52127766} & {1.17720402} \end{bmatrix}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 凡事预则立,不预则废,训练机器学习模型也是如此。数据清洗和预处理是模型训练之前的必要过程,否则模型可能就「废」了。...
    yoku酱阅读 983评论 0 1
  • sklearn、XGBoost、LightGBM的文档阅读小记 文章导航 目录 1.sklearn集成方法 1.1...
    nightwish夜愿阅读 12,693评论 1 49
  • 一个易于理解的scikit-learn教程,可以帮助您开始使用Python机器学习。 使用Python进行机器学习...
    iOSDevLog阅读 13,107评论 0 7
  • 相关链接:Github地址简书地址CSDN地址 总所周知,对于机器学习任务,特别是对于深度学习任务,我们需要创建训...
    MaosongRan阅读 936评论 0 0
  • 站在一个制高点看凤凰,凤凰的美是壮观的,他是这偏远湘西背景一样的东西,吊脚楼河岸凸现在他之上是一些...
    杀少阅读 350评论 0 1