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

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

第一步,导入数据

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

加载 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提供了多种多样的库来完成数据处理的的工作,最流行的三个基础的库有:NumpyMatplotlibPandas。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\) 中是有一项数据是缺失的,此时可以使用 scikit-learn 预处理模型中的 imputer 类来填充缺失项

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} \]

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

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} \]

posted @ 2019-03-02 20:29  范中豪  阅读(4241)  评论(0编辑  收藏  举报