100天机器学习1---数据预处理

数据预处理

1. 导入需要的库

numpy包含数学计算函数
pandas用于导入和管理数据集

import numpy as np
import pandas as pd

2. 导入数据集

数据集通常是.csv格式。csv文件以文本形式保存表格数据。文件的每一行是一条数据记录。我们使用Pandas的**read_csv方法读取本地csv文件作为一个数据帧。然后,从数据帧中制作自变量和因变量的矩阵和向量。

dataset = pd.read_csv('Data.csv')//读取csv文件
X = dataset.iloc[ : , :-1].values//.iloc[行,列]
Y = dataset.iloc[ : , 3].values  // : 全部行 or 列;[a]第a行 or// [a,b,c]第 a,b,c 行 or

3. 处理丢失数据

我们得到的数据很少是完整的。数据可能因为各种原因丢失,为了不降低机器学习模型的性能。需要处理数据。我们可以用整列的平均值或中间值替换丢失的数据。我们用sklearn.preprocessing库中的Imputer类完成这项任务。

from sklearn.preprocessing import Imputer
# axis=0表示按列进行
imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0)
imputer = imputer.fit(X[ : , 1:3])  #求出将X[:. 1:3]中各列的均值
X[ : , 1:3] = imputer.transform(X[ : , 1:3]) #将各列的均值应用到X[:,1:3]中

4. 解析分类数据

分类数据指的是含有标签值而不是数字值的变量。取值范围通常是固定的。需要解析成数字。为了实现这一功能。我们从sklearn.preprocesing库导入LabelEncoder类。

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[ : , 0] = labelencoder_X.fit_transform(X[ : , 0])
#Creating a dummy variable
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()
labelencoder_Y = LabelEncoder()
Y =  labelencoder_Y.fit_transform(Y)
  1. LabelEncoder :将标签编码为0-n_classes-1
    官网参考链接

属性:

classes_:持有每个类的标签。

methods

方法 描述
fit(self, y) 形成标签编码
fit_transform(self, y) 形成标签编码并返回编码后的标签
get_params(self[, deep]) 获取这个估计量的参数
inverse_transform(self, y) 将标签转换为原始编码
set_params(self, **params) 设置此估计量的参数
transform(self, y) 将标签转换为标准包编码
  1. OneHotEncoder:将分类整数特征编码为一键式数字数组。
    注意:y标签的OneHotEncoder应改用LabelBinarizer
    官网参考链接
sklearn.preprocessing.OneHotEncoder(n_values=None, 
categorical_features=None, categories=None, drop=None, 
sparse=True, dtype=<class ‘numpy.float64’>, handle_unknown=’error’)

"""
categorical_features(ColumnTransformer): 指定将那些特征视为分类功能
	1.'all': 所有特征
	2.'array of indices':分类特征索引数组
	3.'mask':长度为n_features且dtype = bool的数组。
drop : ‘first’ or a list/array of shape (n_features,), default=None.
	Specifies a methodology to use to drop one of the categories per feature. 
"""

属性:

属性 描述
categories_ 在拟合过程中确定的每个特征的类别(按X中特征的顺序,并与转换的输出相对应)。 这包括下拉列表中指定的类别(如果有)。
drop_idx_ drop_idx_ [i]是要为每个特征删除的类别的Categories_ [i]中的索引。 如果将保留所有已转换的要素,则为None。
active_features_ 活动特征的索引,表示实际在训练集中出现的值。 仅在n_values为“ auto”时可用。
feature_indices_ 要素范围的指标。 原始数据中的特征i映射到从feature_indices_ [i]到feature_indices_ [i+1]的特征(然后可能被active_features_掩盖)
n_values_ 每个特征的最大值数量。

Methods

方法 描述
fit(self, X[, y]) Fit OneHotEncoder to X.
fit_transform(self, X[, y]) Fit OneHotEncoder to X, then transform X.
get_feature_names(self[, input_features]) Return feature names for output features.
get_params(self[, deep]) Get parameters for this estimator.
inverse_transform(self, X) Convert the back data to the original representation.
set_params(self, **params) Set the parameters of this estimator.
transform(self, X) Transform X using one-hot encoding.

注意:

  • 若X为列表,则可直接将string转为float,若X为array,则无法将string转为float,需先使用LabelEncoder,再使用OneHotEncoder。
  • fit_transform()方法后需再接一个toarray()方法,将输出转为array类型。

5.拆分数据集为测试集合和训练集合

把数据集拆分为两个:一个是用来训练模型的训练集合。另一个是用来验证模型的测试集合。两者比列一般是80:20。我们导入sklearn.crossvalidation库中的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)

train_test_split:将数组或矩阵拆分为随机训练和测试子集
官网参考链接

sklearn.model_selection.train_test_split(*arrays, **options)

"""
*arrays: 具有相同长度的可索引序列
**options:
	1.test_size: float,int or None
	测试集大小
	2.train_size: float, int, or None
	训练集大小
	3.random_state: int, RandomState instance or None
	随机数种子
	4.shuffle:boolean
	拆分前是否对数据进行混洗,默认为True
	5.stratify: array-like or None
	如果不为None,将数据用作类标签以分层方式拆分。默认为None
"""

6.特征缩放

大部分模型算法使用两点间的欧式距离表示,但此特征在幅度、单位和范围姿态问题上变化很大。在距离计算中。高幅度的特征比低幅度的特征权重更大。可用特征标准化Z值归一化解决。导入sklearn.preprocessing库的StandardScalar类。
特征缩放的目的:让梯度下降能够运行的更快一点,让梯度下降收敛所需的循环次数更少一点。以较快的速度找到使代价函数值最小的θ参数。

通过计算训练集中样本的相关统计信息,对每个特征进行独立居中和缩放。然后存储平均值和标准偏差,以使用变换方法在以后的数据上使用。数据集的标准化是许多机器学习估计器的普遍要求:如果单个特征看起来或多或少不像标准正态分布数据(例如均值和单位方差为0的高斯),它们可能会表现不佳。例如,学习算法的目标函数中使用的许多元素(例如支持向量机的RBF内核或线性模型的L1和L2正则化器)都假定所有特征都围绕0居中并且具有相同顺序的方差。如果某个特征的方差比其他特征大几个数量级,则它可能会支配目标函数,并使估计器无法按预期从其他特征中正确学习。
通过传递with_mean = False来避免破坏数据的稀疏结构,该缩放器还可应用于稀疏的CSR或CSC矩阵。

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)

StandardScaler:通过去除均值并缩放到单位方差来标准化特征值

计算公式:z = (x - u) / s    u为均值,s为单位方差
StandardScaler(copy=True, with_mean=True, with_std=True)
"""
若with_mean=False, 则u为0,若with_std=False, 则s=0
copy: 是否将标准化后的值取代原数据。
"""

属性

属性 描述
scale_ 每个要素的数据相对缩放比例。 使用np.sqrt(var_)计算得出。 当with_std = False时等于无。
mean_ 训练集中每个特征的平均值。 with_mean = False时等于无
var_ 训练集中每个要素的方差。 用于计算scale_。 当with_std = False时等于无。
n_samples_seen 估计器为每个要素处理的样本数。

Methods

方法 描述
fit(self, X[, y]) Compute the mean and std to be used for later scaling.
fit_transform(self, X[, y]) Fit to data, then transform it.
get_params(self[, deep]) Get parameters for this estimator.
inverse_transform(self, X[, copy]) Scale back the data to the original representation
partial_fit(self, X[, y]) Online computation of mean and std on X for later scaling.
set_params(self, **params) Set the parameters of this estimator.
transform(self, X[, copy]) Perform standardization by centering and scaling
发布了21 篇原创文章 · 获赞 0 · 访问量 409

猜你喜欢

转载自blog.csdn.net/leemusk/article/details/102955016