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

第一步,导入数据

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

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

最新文章

  1. ionic入门01
  2. VS调试技巧,提高调试效率(转):
  3. 建立树莓派raspberry交叉编译环境以及编译内核
  4. php连接oracle及简单操作
  5. JS 之完美运动框架
  6. jni中的参数含义
  7. SQL AlawaysOn 之五:ISCSI共享磁盘
  8. android学习ProgressBar的简单使用
  9. leetcode:程序员面试技巧
  10. 电子科技大学实验中学PK赛(一)比赛题解
  11. 关于"Linux下使用Windows应用程序的尝试"总结
  12. 克罗内克符号kronecker_delta
  13. 5+ App开发打包指南
  14. 将 DNSCrypt 部署到 Openwrt 路由器上+ DNSmasq 解析国内域名用本地 DNS[ZT+实践]
  15. 在PHP中使用协程实现多任务调度
  16. scrapy-继承默认的user-agent 中间件
  17. 2018.12.31 Failed to load JavaHL Library.错误解决
  18. [BZOJ5120] [2017国家集训队测试]无限之环
  19. mysql的安装以及简单的命令符
  20. CentOS 7 配置阿里云yum源

热门文章

  1. REdis CPU百分百问题分析
  2. 基于模型的特征选择详解 (Embedded & Wrapper)
  3. jquery综合
  4. qscoj 喵哈哈村的打印机游戏 区间dp
  5. 命令行方式登录PostgreSQL
  6. why microsoft named their cloud service Azure?
  7. 包建强的培训课程(14):Android与ReactNative
  8. IDEA一定要懂的32条快捷键
  9. Java核心技术卷一基础知识-第11章-异常、断言、日志和调试-读书笔记
  10. Metasploit Framework(4)信息收集