1. 程式人生 > >sklearn庫常用方法總結

sklearn庫常用方法總結

引言

對於一些開始搞機器學習演算法有害怕下手的小朋友,該如何快速入門,這讓人挺掙扎的。
在從事資料科學的人中,最常用的工具就是R和Python了,每個工具都有其利弊,但是Python在各方面都相對勝出一些,這是因為scikit-learn庫實現了很多機器學習演算法。

載入資料(Data Loading)

我們假設輸入時一個特徵矩陣或者csv檔案。
首先,資料應該被載入記憶體中。
scikit-learn的實現使用了NumPy中的arrays,所以,我們要使用NumPy來載入csv檔案。
以下是從UCI機器學習資料倉庫中下載的資料。

複製程式碼
 1 import numpy as np
2 import urllib 3 # url with dataset 4 url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" 5 # download the file 6 raw_data = urllib.urlopen(url) 7 # load the CSV file as a numpy matrix 8 dataset = np.loadtxt(raw_data, delimiter=",") 9 #
separate the data from the target attributes 10 X = dataset[:,0:7] 11 y = dataset[:,8]
複製程式碼

我們要使用該資料集作為例子,將特徵矩陣作為X,目標變數作為y。

注意事項:

(1)可以用瀏覽器開啟那個url,把資料檔案儲存在本地,然後直接用 np.loadtxt('data.txt', delemiter=",") 就可以載入資料了;

(2)X = dataset[:, 0:7]的意思是:把dataset中的所有行,所有0-7列的資料都儲存在X中;

資料歸一化(Data Normalization)

大多數機器學習演算法中的梯度方法對於資料的縮放和尺度都是很敏感的,在開始跑演算法之前,我們應該進行歸一化或者標準化的過程,這使得特徵資料縮放到0-1範圍中。scikit-learn提供了歸一化的方法,具體解釋參考http://scikit-learn.org/stable/modules/preprocessing.html

複製程式碼
1 from sklearn import preprocessing
2 #scale the data attributes
3 scaled_X = preprocessing.scale(X)
4 
5 # normalize the data attributes
6 normalized_X = preprocessing.normalize(X)
7 
8 # standardize the data attributes
9 standardized_X = preprocessing.scale(X)
複製程式碼

特徵選擇(Feature Selection)

在解決一個實際問題的過程中,選擇合適的特徵或者構建特徵的能力特別重要。這成為特徵選擇或者特徵工程。
特徵選擇時一個很需要創造力的過程,更多的依賴於直覺和專業知識,並且有很多現成的演算法來進行特徵的選擇。
下面的樹演算法(Tree algorithms)計算特徵的資訊量:

程式碼:

複製程式碼
1 from sklearn import metrics
2 from sklearn.ensemble import ExtraTreesClassifier
3 model = ExtraTreesClassifier()
4 model.fit(X, y)
5 # display the relative importance of each attribute
6 print(model.feature_importances_)
複製程式碼

輸出每個特徵的重要程度:

[ 0.13784722  0.15383598  0.25451389  0.17476852  0.02847222  0.12314815  0.12741402]

演算法的使用

scikit-learn實現了機器學習的大部分基礎演算法,讓我們快速瞭解一下。

邏輯迴歸(官方文件

大多數問題都可以歸結為二元分類問題。這個演算法的優點是可以給出資料所在類別的概率。

複製程式碼
 1 from sklearn import metrics
 2 from sklearn.linear_model import LogisticRegression
 3 model = LogisticRegression()
 4 model.fit(X, y)
 5 print('MODEL')
 6 print(model)
 7 # make predictions
 8 expected = y
 9 predicted = model.predict(X)
10 # summarize the fit of the model
11 print('RESULT')
12 print(metrics.classification_report(expected, predicted))
13 print('CONFUSION MATRIX')
14 print(metrics.confusion_matrix(expected, predicted))
複製程式碼

結果:

複製程式碼
 1 MODEL
 2 LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
 3           intercept_scaling=1, max_iter=100, multi_class='ovr',
 4           penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
 5           verbose=0)
 6 RESULT
 7              precision    recall  f1-score   support
 8 
 9         0.0       1.00      1.00      1.00         4
10         1.0       1.00      1.00      1.00         6
11 
12 avg / total       1.00      1.00      1.00        10
13 
14 CONFUSION MATRIX
15 [[4 0]
16  [0 6]]
複製程式碼

輸出結果中的各個引數資訊,可以參考官方文件。

樸素貝葉斯(官方文件

這也是著名的機器學習演算法,該方法的任務是還原訓練樣本資料的分佈密度,其在多類別分類中有很好的效果。

複製程式碼
 1 from sklearn import metrics
 2 from sklearn.naive_bayes import GaussianNB
 3 model = GaussianNB()
 4 model.fit(X, y)
 5 print('MODEL')
 6 print(model)
 7 # make predictions
 8 expected = y
 9 predicted = model.predict(X)
10 # summarize the fit of the model
11 print('RESULT')
12 print(metrics.classification_report(expected, predicted))
13 print('CONFUSION MATRIX')
14 print(metrics.confusion_matrix(expected, predicted))
複製程式碼

結果:

複製程式碼
MODEL
GaussianNB()
RESULT
             precision    recall  f1-score   support

        0.0       0.80      1.00      0.89         4
        1.0       1.00      0.83      0.91         6

avg / total       0.92      0.90      0.90        10

CONFUSION MATRIX
[[4 0]
 [1 5]]
複製程式碼

k近鄰(官方文件

k近鄰演算法常常被用作是分類演算法一部分,比如可以用它來評估特徵,在特徵選擇上我們可以用到它。

複製程式碼
 1 from sklearn import metrics
 2 from sklearn.neighbors import KNeighborsClassifier
 3 # fit a k-nearest neighbor model to the data
 4 model = KNeighborsClassifier()
 5 model.fit(X, y)
 6 print(model)
 7 # make predictions
 8 expected = y
 9 predicted = model.predict(X)
10 # summarize the fit of the model
11 print(metrics.classification_report(expected, predicted))
12 print(metrics.confusion_matrix(expected, predicted))
複製程式碼

結果:

複製程式碼
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_neighbors=5, p=2, weights='uniform')
             precision    recall  f1-score   support

        0.0       0.75      0.75      0.75         4
        1.0       0.83      0.83      0.83         6

avg / total       0.80      0.80      0.80        10

[[3 1]
 [1 5]]
複製程式碼

決策樹(官方文件

分類與迴歸樹(Classification and Regression Trees ,CART)演算法常用於特徵含有類別資訊的分類或者回歸問題,這種方法非常適用於多分類情況。

複製程式碼
 1 from sklearn import metrics
 2 from sklearn.tree import DecisionTreeClassifier
 3 # fit a CART model to the data
 4 model = DecisionTreeClassifier()
 5 model.fit(X, y)
 6 print(model)
 7 # make predictions
 8 expected = y
 9 predicted = model.predict(X)
10 # summarize the fit of the model
11 print(metrics.classification_report(expected, predicted))
12 print(metrics.confusion_matrix(expected, predicted))
複製程式碼

結果

複製程式碼
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            random_state=None, splitter='best')
             precision    recall  f1-score   support

        0.0       1.00      1.00      1.00         4
        1.0       1.00      1.00      1.00         6

avg / total       1.00      1.00      1.00        10

[[4 0]
 [0 6]]
複製程式碼

支援向量機(官方文件

SVM是非常流行的機器學習演算法,主要用於分類問題,如同邏輯迴歸問題,它可以使用一對多的方法進行多類別的分類。

複製程式碼
 1 from sklearn import metrics
 2 from sklearn.svm import SVC
 3 # fit a SVM model to the data
 4 model = SVC()
 5 model.fit(X, y)
 6 print(model)
 7 # make predictions
 8 expected = y
 9 predicted = model.predict(X)
10 # summarize the fit of the model
11 print(metrics.classification_report(expected, predicted))
12 print(metrics.confusion_matrix(expected, predicted))
複製程式碼

結果

複製程式碼
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
             precision    recall  f1-score   support

        0.0       1.00      1.00      1.00         4
        1.0       1.00      1.00      1.00         6

avg / total       1.00      1.00      1.00        10

[[4 0]
 [0 6]]
複製程式碼

除了分類和迴歸演算法外,scikit-learn提供了更加複雜的演算法,比如聚類演算法,還實現了演算法組合的技術,如Bagging和Boosting演算法。

如何優化演算法引數

一項更加困難的任務是構建一個有效的方法用於選擇正確的引數,我們需要用搜索的方法來確定引數。scikit-learn提供了實現這一目標的函式。
下面的例子是一個進行正則引數選擇的程式:

GridSearchCV官方文件1(模組使用) 官方文件2 (原理詳解)

複製程式碼
 1 import numpy as np
 2 from sklearn.linear_model import Ridge
 3 from sklearn.grid_search import GridSearchCV
 4 # prepare a range of alpha values to test
 5 alphas = np.array([1,0.1,0.01,0.001,0.0001,0])
 6 # create and fit a ridge regression model, testing each alpha
 7 model = Ridge()
 8 grid = GridSearchCV(estimator=model, param_grid=dict(alpha=alphas))
 9 grid.fit(X, y)
10 print(grid)
11 # summarize the results of the grid search
12 print(grid.best_score_)
13 print(grid.best_estimator_.alpha)
複製程式碼

結果:

複製程式碼
GridSearchCV(cv=None, error_score='raise',
       estimator=Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, solver='auto', tol=0.001),
       fit_params={}, iid=True, loss_func=None, n_jobs=1,
       param_grid={'alpha': array([  1.00000e+00,   1.00000e-01,   1.00000e-02,   1.00000e-03,
         1.00000e-04,   0.00000e+00])},
       pre_dispatch='2*n_jobs', refit=True, score_func=None, scoring=None,
       verbose=0)
-5.59572064238
0.0
複製程式碼

有時隨機從給定區間中選擇引數是很有效的方法,然後根據這些引數來評估演算法的效果進而選擇最佳的那個。

RandomizedSearchCV官方文件(模組使用)官方文件2 (原理詳解)

複製程式碼
 1 import numpy as np
 2 from scipy.stats import uniform as sp_rand
 3 from sklearn.linear_model import Ridge
 4 from sklearn.grid_search import RandomizedSearchCV
 5 # prepare a uniform distribution to sample for the alpha parameter
 6 param_grid = {'alpha': sp_rand()}
 7 # create and fit a ridge regression model, testing random alpha values
 8 model = Ridge()
 9 rsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
10 rsearch.fit(X, y)
11 print(rsearch)
12 # summarize the results of the random parameter search
13 print(rsearch.best_score_)
14 print(rsearch.best_estimator_.alpha)
複製程式碼