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

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

第一步,导入数据

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

加载 nii 文件并转为 numpy 数组babel

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 基本是必需的dom

在导入库时,若是库名较长,最好能赋予其缩写形式,以便在以后的使用中能够使用简写。如机器学习

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'] \]spa

可见 \(x\) 中是有一项数据是缺失的,此时能够使用 scikit-learn 预处理模型中的 imputer 类来填充缺失项code

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

相关文章
相关标签/搜索