1. 程式人生 > 其它 >Python玩機器學習簡易教程

Python玩機器學習簡易教程

本文介紹利用Python和Python的機器學習庫scikit-learn完成一個端到端的機器學習專案。

俗話說,“師傅領進門,修行在個人”。本文就是扮演領進門這種角色,至於各位看官能夠修行到什麼境界,全憑自己。

  • 1 設定環境
  • 2 匯入所需庫和模組
  • 3 載入資料集
  • 4 資料集劃分為訓練集和測試集
  • 5 資料預處理
  • 6 引數調優
  • 7 模型優化(交叉驗證)
  • 8 全資料擬合
  • 9 模型評估
  • 10 模型儲存

1 設定環境

檢查電腦是否安裝了Python以及相應庫numpy/pandas/scikit-learn。 若是沒有,推薦一鍵式安裝Anaconda(安裝教程)。 安裝好後,測試一下版本號。 Code:

import sysprint("Python版本:%s" %sys.version)
import numpyprint("numpy版本:%s" %numpy.__version__)
import matplotlibprint("matplotlib版本:%s" %matplotlib.__version__)
import pandasprint("pandas版本:%s" %pandas.__version__)
import sklearnprint("sklearn版本:%s" %sklearn.__version__)

Result:

2 匯入所需庫和模組

科學計算庫numpy 資料處理和分析庫pandas 資料集劃分模組train_test_split 資料預處理模組preprocessing 資料演算法模組RandomForestRegressor 模型優化模組make_pipeline和GridSearchCV 模型評估模組mean_squared_error和r2_score 模型儲存模組joblib

Code:

import numpy as np 
import pandas as pd 
from sklearn.model_selection 
import train_test_splitfrom sklearn 
import preprocessingfrom sklearn.ensemble 
import RandomForestRegressorfrom sklearn.pipeline 
import make_pipelinefrom sklearn.model_selection 
import GridSearchCVfrom sklearn.metrics 
import mean_squared_error, r2_scorefrom sklearn.externals 
import joblib

3 載入資料集

俗話說“巧婦難為無米之炊”。 “資料”是原材料。 本教程使用wine data資料集。 載入資料集和資料簡單探索性分析。 Code:

dataset_url = "http://mlr.cs.umass.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"data = pd.read_csv(dataset_url, sep = ";")print(data.head())print(data.shape)print(data.describe())

4 資料集劃分為訓練集和測試集

資料集劃分目的用來評估模型的效能和效果。 Code:

y = data.qualityX = data.drop("quality", axis = 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 123, stratify=y)

train_test_split模組的引數說明:

  • test_size: 設定測試集佔總樣本的比例
  • random_state: 設定隨機種子,便於可重複性試驗
  • stratify=y:讓訓練集和測試集具有相似性,服務模型評估

5 資料預處理

使用Transformer API 做資料預處理,具體步驟如下:

  • 對訓練資料集擬合生成一個轉換器(儲存均值和標準差)
  • 利用轉換器對訓練集做預處理
  • 利用轉換器對測試集做預處理(使用了與訓練集相同的均值和標準差) 程式碼如下: 有時候,我們設定交叉驗證管道(pipeline)時,不需要手工設定Transformer API,我們可以建立一個管道物件,如下: 這個pipeline物件首先使用StandardScaler()對資料做預處理,然後用隨機森林迴歸演算法擬合生成一個模型。
    1. pipeline = make_pipeline(preprocessing.StandardScaler(), RandomForestRegressor(n_estimators=100))
    2. scaler = preprocessing.StandardScaler().fit(X_train)
    3. X_train_scaled = scaler.transform(X_train)
    4. print(X_train_scaled.mean(axis=0))
    5. print(X_train_scaled.std(axis=0))
    6. X_test_scaled = scaler.transform(X_test)
    7. print(X_test_scaled.mean(axis=0))
    8. print(X_test_scaled.std(axis=0))

6 引數調優

一個模型裡面包括兩個方面的引數:

  • 方面一:模型引數,從資料中最終可以學習到的引數,例如迴歸演算法的係數。
  • 方面二:超引數,從資料中學習不到的引數,在做模型之前需要事先設定好的引數。

舉例說明:隨機森林迴歸演算法的超引數 隨機森林需要生成多少棵樹? 隨機森林中樹產生的標準?(MSE或者MAE) 下面羅列隨機森林迴歸演算法的超引數 程式碼如下:

print(pipeline.get_params())

與超引數相關結果如下:

RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None,max_features='auto', max_leaf_nodes=None,min_impurity_split=1e-07, min_samples_leaf=1,min_samples_split=2, min_weight_fraction_leaf=0.0,n_estimators=100, n_jobs=1, oob_score=False, random_state=None,verbose=0, warm_start=False)

交叉驗證時設定需要調整的超引數 程式碼如下:

hyperparameters = { 'randomforestregressor__max_features' : ['auto', 'sqrt', 'log2'],'randomforestregressor__max_depth': [None, 5, 3, 1]}

7 模型優化(交叉驗證)

交叉驗證是模型效能評估的一種可靠方法。 常用10-折交叉驗證為例。

  1. 把資料集劃分成10等分;
  2. 利用9等分訓練模型;
  3. 剩下的1等分評估模型效果;
  4. 重複2和3步10次,每次採用不同的1等分用來做模型驗證;
  5. 聚合10次模型評估效能,當做模型效能最終值;

基於管道物件實現交叉驗證 程式碼

clf = GridSearchCV(pipeline, hyperparameters, cv=10)clf.fit(X_train, y_train)print(clf.best_params_)

結果發現超引數預設值為最佳。

8 全資料擬合

當使用交叉驗證方法找到最佳的超引數後,為了進一步改善模型的效能需要對全部訓練資料做模型擬合。 GridSearchCV已經用最佳超引數對全部訓練資料集做了模型擬合,程式碼檢視如下。

print(clf.refit)

結果為True

9 模型評估

在測試集上做模型評估 程式碼如下

y_pred = clf.predict(X_test)print(r2_score(y_test, y_pred))print(mean_squared_error(y_test, y_pred))

結果如下: 0.465495005751 0.344901875

截止到目前,基於隨機森林迴歸模型,已經完成了。這個模型是否為解決問題的最佳模型呢?可以從以下三方面思考。

  1. 模型能否解決好問題?
  2. 模型的效能相對於基準線是什麼情況?
  3. 模型的效能優化點有哪些?

改善模型效能的常用方法總結。

  • 收集更多的資料
  • 花更多時間做好特徵工程
  • 嘗試其他模型和演算法(正則化迴歸、提升樹等)
  • 吸收更多有用的領域知識
  • 採用整合學習的思想

10 模型儲存

模型儲存,以便後續使用和模型部署與實施。 程式碼

joblib.dump(clf, 'rf_regressor.pkl')
clf2 = joblib.load('rf_regressor.pkl')
clf2.predict(X_test)

附錄:完整程式碼參考

## Python玩機器學習簡易教程##開始時間:2017年8月24日##結束時間:2017年9月16日## 第一步:設定環境
import sysprint("Python版本:%s" %sys.version)
import numpyprint("numpy版本:%s" %numpy.__version__)
import matplotlibprint("matplotlib版本:%s" %matplotlib.__version__)
import pandasprint("pandas版本:%s" %pandas.__version__)
import sklearnprint("sklearn版本:%s" %sklearn.__version__)
## 第二步:匯入所需庫
import numpy as np 
import pandas as pd 
from sklearn.model_selection 
import train_test_splitfrom sklearn 
import preprocessingfrom sklearn.ensemble 
import RandomForestRegressorfrom sklearn.pipeline 
import make_pipelinefrom sklearn.model_selection 
import GridSearchCVfrom sklearn.metrics 
import mean_squared_error, r2_scorefrom sklearn.externals 
import joblib
## 第三步:載入資料集
dataset_url = "http://mlr.cs.umass.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
data = pd.read_csv(dataset_url, sep = ";")
print(data.head())print(data.shape)
print(data.describe())
## 第四步:資料集劃分
y = data.qualityX = data.drop("quality", axis = 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 123, stratify=y)
## 第五步:資料預處理## 對訓練集的所有特徵進行標準化處理
pipeline = make_pipeline(preprocessing.StandardScaler(), RandomForestRegressor(n_estimators=100))
## 第六步:引數調優
print(pipeline.get_params())
hyperparameters = { 'randomforestregressor__max_features' : ['auto', 'sqrt', 'log2'], 'randomforestregressor__max_depth': [None, 5, 3, 1]}
## 第七步:模型優化(交叉驗證)
clf = GridSearchCV(pipeline, hyperparameters, cv=10)
clf.fit(X_train, y_train)print(clf.best_params_)
## 第八步:全資料擬合print(clf.refit)
## 第九步:模型評估
y_pred = clf.predict(X_test)
print(r2_score(y_test, y_pred))
print(mean_squared_error(y_test, y_pred))
## 第十步:模型儲存
joblib.dump(clf, 'rf_regressor.pkl')
clf2 = joblib.load('rf_regressor.pkl')
# 載入模型預測新的資料集clf2.predict(X_test)