NumPy :一個用Python實現(xiàn)的科學計算包
1. 一個強大的N維數(shù)組對象Array
2. 快速的數(shù)學運算陣列
3. 實用的線性代數(shù)、傅里葉變換和隨機數(shù)生產(chǎn)函數(shù)
pandas : 解決數(shù)據(jù)分析的數(shù)據(jù)分析包
1. 處理缺失數(shù)據(jù)
2. 可以讓數(shù)據(jù)規(guī)范化、明確化
3. 數(shù)據(jù)分割伶椿、合并
4. 加載Excel文件(xxx.csv),數(shù)據(jù)庫和保存/加載數(shù)據(jù)從超速 HDF5格式
5. 生成日期范圍和頻率轉(zhuǎn)換,移動窗口統(tǒng)計,線性回歸移動窗口,日期轉(zhuǎn)移和滯后等赋除。
sklearn.preprocessing:數(shù)據(jù)預處理
- 關于 sklearn 更多內(nèi)容
- 這里主要用來處理缺失數(shù)據(jù)(常用的三種方法)
- 刪除 :最簡單最直接的方法,很多時候也是最有效的方法,這種做法的缺點是可能會導致信息丟失纫溃。
- 補全 :平均數(shù)墨林、中位數(shù)赁酝、眾數(shù)、最大值旭等、最小值酌呆、固定值、插值等等搔耕。用規(guī)則或模型將缺失數(shù)據(jù)補全隙袁,這種做法的缺點是可能會引入噪聲
- 忽略 :有一些模型,如隨機森林弃榨,自身能夠處理數(shù)據(jù)缺失的情況菩收,在這種情況下不需要對缺失數(shù)據(jù)做任何的處理,這種做法的缺點是在模型的選擇上有局限鲸睛。
Imputer :sklearn.preprocessing中的一個類娜饵,提供了基本的策略將缺失值(NaN/nan),使用均值、中值或最常見的價值缺失值的行或列
LabelEncoder :對不連續(xù)的數(shù)字或者文本進行編號
OneHotEncoder:用于將表示分類的數(shù)據(jù)擴維
OneHotEncoder 輸入必須是int數(shù)組官辈,把類別數(shù)據(jù)轉(zhuǎn)換成多列0,1數(shù)據(jù)箱舞。
LabelEncoder遍坟,把數(shù)據(jù)轉(zhuǎn)化成int整形
源數(shù)據(jù) Data.csv
第2列和第三列中分別有一項數(shù)據(jù)是空白的,這就是缺失數(shù)據(jù)(NaN/nan)
Python:
首先在右側(cè)File explorer 找到你的數(shù)據(jù)所在文件夾
在代碼中導入數(shù)據(jù)
#處理矩陣
import numpy as np
#數(shù)據(jù)可視化--畫圖
import matplotlib.pyplot as plt
#解決數(shù)據(jù)分析
import pandas as pd
dataset = pd.read_csv('Data.csv')
# .iloc[] 根據(jù)索引選擇的位置
# 獲取到最后一個之前-1表示倒數(shù)第一
X = dataset.iloc[:,:-1].values
# 單獨拿出最后一列數(shù)據(jù) Purchased 晴股,Purchased的索引是3
# [:,3] 所有類的第三列的所有數(shù)據(jù)
y = dataset.iloc[:,3].values
#處理缺失數(shù)據(jù)
from sklearn.preprocessing import Imputer
# strategy 補缺值方式 mean(默認) 平均值 median 中值 most_frequent 出現(xiàn)次數(shù)最多的
# axis 0(默認) - 列 1 - 行
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0, copy = True)
#Country 只有3種
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
#數(shù)據(jù)規(guī)范化
#OneHotEncoder - 用于將表示分類的數(shù)據(jù)擴維
#LabelEncoder - 對不連續(xù)的數(shù)字或者文本進行編號
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
#用LabelEncoder 把 需要轉(zhuǎn)換的第一列轉(zhuǎn)化成int型數(shù)組
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)
缺失數(shù)據(jù)就已經(jīng)通過求平局值的方式補全愿伴,并且把Country轉(zhuǎn)成了所需要的數(shù)字代表。
sklearn.cross_validation.train_test_split 把數(shù)據(jù)集分成訓練集和測試集
# 把數(shù)據(jù)集分成訓練集和測試集
from sklearn.cross_validation import train_test_split
# test_size 測試數(shù)據(jù)20%
#random_state 當別人重新運行你的代碼的時候就能得到完全一樣的結(jié)果电湘,復現(xiàn)和你一樣的過程,如果你設置為 默認的None公般,則會隨機選擇一個種子,準確度可能會有波動
# 避免過擬合,采用交叉驗證胡桨,驗證集占訓練集20%官帘,固定隨機種子(random_state)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)