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

Day1 Data PreProcessing github: 100-Days-Of-ML-Code
1.导入两个常用的python库,numpy, pandas

import numpy as np import pandas as pd

2.读取数据文件
dataset = pd.read_csv("Data.csv") X = dataset.iloc[:,:-1].values Y = dataset.iloc[:,3].values

【机器学习1/100天-数据预处理】pd函数read_csv读取数据文件
而后dataframe.iloc按照位置选取数据,划分成X和Y
3.缺省值处理 使用sklearn.preprocessing.Imputer处理缺省值,以均值代替NaN
from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0) imputer = imputer.fit(X[:,1:3]) X[:,1:3] = imputer.transform(X[:,1:3])

4.将文本数据编码 使用sklearn.preprocessing.LabelEncoder和OneHotEncoder编码数据。
from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:,0] = labelencoder_X.fit_transform(X[:,0])onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() labelEncoder_Y = LabelEncoder() Y = labelEncoder_Y.fit_transform(Y)

LabelEncoder文本变数值,OneHotEncoder数值变OneHot编码
5.划分训练集和测试集 在新版本中train_test_split函数位于model_select module
from sklearn.cross_validation import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2,random_state=0)

6.数据标准化
from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.fit_transform(X_test)

    推荐阅读