佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > 一文搞懂Python Sklearn庫(kù)使用

一文搞懂Python Sklearn庫(kù)使用

熱門標(biāo)簽:美圖手機(jī) 網(wǎng)站文章發(fā)布 呼叫中心市場(chǎng)需求 智能手機(jī) 銀行業(yè)務(wù) 檢查注冊(cè)表項(xiàng) 鐵路電話系統(tǒng) 服務(wù)器配置

Python sklearn庫(kù)是一個(gè)豐富的機(jī)器學(xué)習(xí)庫(kù),里面包含內(nèi)容太多,這里對(duì)一些工程里常用的操作做個(gè)簡(jiǎn)要的概述,以后還會(huì)根據(jù)自己用的進(jìn)行更新。

1、LabelEncoder

簡(jiǎn)單來(lái)說(shuō) LabelEncoder 是對(duì)不連續(xù)的數(shù)字或者文本進(jìn)行按序編號(hào),可以用來(lái)生成屬性/標(biāo)簽

from sklearn.preprocessing import LabelEncoder
encoder=LabelEncoder()
encoder.fit([1,3,2,6])
t=encoder.transform([1,6,6,2])
print(t)

輸出: [0 3 3 1]

2、OneHotEncoder

OneHotEncoder 用于將表示分類的數(shù)據(jù)擴(kuò)維,將[[1],[2],[3],[4]]映射為 0,1,2,3的位置為1(高維的數(shù)據(jù)自己可以測(cè)試):

from sklearn.preprocessing import OneHotEncoder
oneHot=OneHotEncoder()#聲明一個(gè)編碼器
oneHot.fit([[1],[2],[3],[4]])
print(oneHot.transform([[2],[3],[1],[4]]).toarray())

輸出:[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[1. 0. 0. 0.]
[0. 0. 0. 1.]]
正如keras中的keras.utils.to_categorical(y_train, num_classes)

3、sklearn.model_selection.train_test_split隨機(jī)劃分訓(xùn)練集和測(cè)試集

一般形式:
train_test_split是交叉驗(yàn)證中常用的函數(shù),功能是從樣本中隨機(jī)的按比例選取train data和testdata,形式為:

X_train,X_test, y_train, y_test =train_test_split(train_data,train_target,test_size=0.2, train_size=0.8,random_state=0)

參數(shù)解釋:
- train_data:所要?jiǎng)澐值臉颖咎卣骷?
- train_target:所要?jiǎng)澐值臉颖窘Y(jié)果
- test_size:測(cè)試樣本占比,如果是整數(shù)的話就是樣本的數(shù)量

-train_size:訓(xùn)練樣本的占比,(注:測(cè)試占比和訓(xùn)練占比任寫一個(gè)就行)
- random_state:是隨機(jī)數(shù)的種子。
- 隨機(jī)數(shù)種子:其實(shí)就是該組隨機(jī)數(shù)的編號(hào),在需要重復(fù)試驗(yàn)的時(shí)候,保證得到一組一樣的隨機(jī)數(shù)。比如你每次都填1,其他參數(shù)一樣的情況下你得到的隨機(jī)數(shù)組是一樣的。但填0或不填,每次都會(huì)不一樣。
隨機(jī)數(shù)的產(chǎn)生取決于種子,隨機(jī)數(shù)和種子之間的關(guān)系遵從以下兩個(gè)規(guī)則:
- 種子不同,產(chǎn)生不同的隨機(jī)數(shù);種子相同,即使實(shí)例不同也產(chǎn)生相同的隨機(jī)數(shù)。

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
iris=load_iris()
train=iris.data
target=iris.target
# 避免過(guò)擬合,采用交叉驗(yàn)證,驗(yàn)證集占訓(xùn)練集20%,固定隨機(jī)種子(random_state)
train_X,test_X, train_y, test_y = train_test_split(train,
                                                   target,
                                                   test_size = 0.2,
                                                   random_state = 0)
print(train_y.shape)

得到的結(jié)果數(shù)據(jù):train_X : 訓(xùn)練集的數(shù)據(jù),train_Y:訓(xùn)練集的標(biāo)簽,對(duì)應(yīng)test 為測(cè)試集的數(shù)據(jù)和標(biāo)簽


4、pipeline

本節(jié)參考與文章:用 Pipeline 將訓(xùn)練集參數(shù)重復(fù)應(yīng)用到測(cè)試集
pipeline 實(shí)現(xiàn)了對(duì)全部步驟的流式化封裝和管理,可以很方便地使參數(shù)集在新數(shù)據(jù)集上被重復(fù)使用。

pipeline 可以用于下面幾處:

  • 模塊化 Feature Transform,只需寫很少的代碼就能將新的 Feature 更新到訓(xùn)練集中。
  • 自動(dòng)化 Grid Search,只要預(yù)先設(shè)定好使用的 Model 和參數(shù)的候選,就能自動(dòng)搜索并記錄最佳的 Model。
  • 自動(dòng)化 Ensemble Generation,每隔一段時(shí)間將現(xiàn)有最好的 K 個(gè) Model 拿來(lái)做 Ensemble。

問(wèn)題是要對(duì)數(shù)據(jù)集 Breast Cancer Wisconsin 進(jìn)行分類,
該數(shù)據(jù)集包含 569 個(gè)樣本,第一列 ID,第二列類別(M=惡性腫瘤,B=良性腫瘤),
第 3-32 列是實(shí)數(shù)值的特征。

我們要用 Pipeline 對(duì)訓(xùn)練集和測(cè)試集進(jìn)行如下操作:

  • 先用 StandardScaler 對(duì)數(shù)據(jù)集每一列做標(biāo)準(zhǔn)化處理,(是 transformer)
  • 再用 PCA 將原始的 30 維度特征壓縮的 2 維度,(是 transformer)
  • 最后再用模型 LogisticRegression。(是 Estimator)
  • 調(diào)用 Pipeline 時(shí),輸入由元組構(gòu)成的列表,每個(gè)元組第一個(gè)值為變量名,元組第二個(gè)元素是 sklearn 中的 transformer
  • 或 Estimator。

注意中間每一步是 transformer,即它們必須包含 fit 和 transform 方法,或者 fit_transform。
最后一步是一個(gè) Estimator,即最后一步模型要有 fit 方法,可以沒(méi)有 transform 方法。

然后用 Pipeline.fit對(duì)訓(xùn)練集進(jìn)行訓(xùn)練,pipe_lr.fit(X_train, y_train)
再直接用 Pipeline.score 對(duì)測(cè)試集進(jìn)行預(yù)測(cè)并評(píng)分 pipe_lr.score(X_test, y_test)

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
 
from sklearn.pipeline import Pipeline
#需要聯(lián)網(wǎng)
df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data',
                 header=None)
                                 # Breast Cancer Wisconsin dataset
X, y = df.values[:, 2:], df.values[:, 1]
encoder = LabelEncoder()
y = encoder.fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)
pipe_lr = Pipeline([('sc', StandardScaler()),
                    ('pca', PCA(n_components=2)),
                    ('clf', LogisticRegression(random_state=1))
                    ])
pipe_lr.fit(X_train, y_train)
print('Test accuracy: %.3f' % pipe_lr.score(X_test, y_test))

還可以用來(lái)選擇特征:

例如用 SelectKBest 選擇特征,
分類器為 SVM,

anova_filter = SelectKBest(f_regression, k=5)
clf = svm.SVC(kernel='linear')
anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)])

當(dāng)然也可以應(yīng)用 K-fold cross validation:

Pipeline 的工作方式:

當(dāng)管道 Pipeline 執(zhí)行 fit 方法時(shí),
首先 StandardScaler 執(zhí)行 fit 和 transform 方法,
然后將轉(zhuǎn)換后的數(shù)據(jù)輸入給 PCA,
PCA 同樣執(zhí)行 fit 和 transform 方法,
再將數(shù)據(jù)輸入給 LogisticRegression,進(jìn)行訓(xùn)練。

5 perdict 直接返回預(yù)測(cè)值

predict_proba返回每組數(shù)據(jù)預(yù)測(cè)值的概率,每行的概率和為1,如訓(xùn)練集/測(cè)試集有 下例中的兩個(gè)類別,測(cè)試集有三個(gè),則 predict返回的是一個(gè) 3*1的向量,而 predict_proba 返回的是 3*2維的向量,如下結(jié)果所示。

# conding :utf-8
from sklearn.linear_model import LogisticRegression
import numpy as np
 
x_train = np.array([[1, 2, 3],
                    [1, 3, 4],
                    [2, 1, 2],
                    [4, 5, 6],
                    [3, 5, 3],
                    [1, 7, 2]])
 
y_train = np.array([3, 3, 3, 2, 2, 2])
 
x_test = np.array([[2, 2, 2],
                   [3, 2, 6],
                   [1, 7, 4]])
 
clf = LogisticRegression()
clf.fit(x_train, y_train)
 
# 返回預(yù)測(cè)標(biāo)簽
print(clf.predict(x_test))
 
# 返回預(yù)測(cè)屬于某標(biāo)簽的概率
print(clf.predict_proba(x_test))

6 sklearn.metrics中的評(píng)估方法

1. sklearn.metrics.roc_curve(true_y. pred_proba_score, pos_labal)

計(jì)算roc曲線,roc曲線有三個(gè)屬性:fpr, tpr,和閾值,因此該函數(shù)返回這三個(gè)變量,l

2. sklearn.metrics.auc(x, y, reorder=False):

計(jì)算AUC值,其中x,y分別為數(shù)組形式,根據(jù)(xi, yi)在坐標(biāo)上的點(diǎn),生成的曲線,然后計(jì)算AUC值;

import numpy as np
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
y = np.array([1,0,2,2])
pred = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y, pred, pos_label=2)
print(tpr)
print(fpr)
print(thresholds)
print(auc(fpr, tpr))

3. sklearn.metrics.roc_auc_score(true_y, pred_proba_y)

直接根據(jù)真實(shí)值(必須是二值)、預(yù)測(cè)值(可以是0/1, 也可以是proba值)計(jì)算出auc值,中間過(guò)程的roc計(jì)算省略

7 GridSearchCV

GridSearchCV,它存在的意義就是自動(dòng)調(diào)參,只要把參數(shù)輸進(jìn)去,就能給出最優(yōu)化的結(jié)果和參數(shù)。但是這個(gè)方法適合于小數(shù)據(jù)集,一旦數(shù)據(jù)的量級(jí)上去了,很難得出結(jié)果。這個(gè)時(shí)候就是需要?jiǎng)幽X筋了。數(shù)據(jù)量比較大的時(shí)候可以使用一個(gè)快速調(diào)優(yōu)的方法——坐標(biāo)下降。它其實(shí)是一種貪心算法:拿當(dāng)前對(duì)模型影響最大的參數(shù)調(diào)優(yōu),直到最優(yōu)化;再拿下一個(gè)影響最大的參數(shù)調(diào)優(yōu),如此下去,直到所有的參數(shù)調(diào)整完畢。這個(gè)方法的缺點(diǎn)就是可能會(huì)調(diào)到局部最優(yōu)而不是全局最優(yōu),但是省時(shí)間省力,巨大的優(yōu)勢(shì)面前,還是試一試吧,后續(xù)可以再拿bagging再優(yōu)化。

回到sklearn里面的GridSearchCV,GridSearchCV用于系統(tǒng)地遍歷多種參數(shù)組合,通過(guò)交叉驗(yàn)證確定最佳效果參數(shù)。

GridSearchCV的sklearn官方網(wǎng)址:http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV

classsklearn.model_selection.GridSearchCV(estimator,param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True,cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise',return_train_score=True)

常用參數(shù)解讀

estimator:所使用的分類器,如estimator=RandomForestClassifier(min_samples_split=100,min_samples_leaf=20,max_depth=8,max_features='sqrt',random_state=10), 并且傳入除需要確定最佳的參數(shù)之外的其他參數(shù)。每一個(gè)分類器都需要一個(gè)scoring參數(shù),或者score方法。

param_grid:值為字典或者列表,即需要最優(yōu)化的參數(shù)的取值,param_grid =param_test1,param_test1 = {'n_estimators':range(10,71,10)}。

scoring :準(zhǔn)確度評(píng)價(jià)標(biāo)準(zhǔn),默認(rèn)None,這時(shí)需要使用score函數(shù);或者如scoring='roc_auc',根據(jù)所選模型不同,評(píng)價(jià)準(zhǔn)則不同。字符串(函數(shù)名),或是可調(diào)用對(duì)象,需要其函數(shù)簽名形如:scorer(estimator, X, y);如果是None,則使用estimator的誤差估計(jì)函數(shù)。

cv :交叉驗(yàn)證參數(shù),默認(rèn)None,使用三折交叉驗(yàn)證。指定fold數(shù)量,默認(rèn)為3,也可以是yield訓(xùn)練/測(cè)試數(shù)據(jù)的生成器。

refit :默認(rèn)為True,程序?qū)?huì)以交叉驗(yàn)證訓(xùn)練集得到的最佳參數(shù),重新對(duì)所有可用的訓(xùn)練集與開(kāi)發(fā)集進(jìn)行,作為最終用于性能評(píng)估的最佳模型參數(shù)。即在搜索參數(shù)結(jié)束后,用最佳參數(shù)結(jié)果再次fit一遍全部數(shù)據(jù)集。

iid:默認(rèn)True,為True時(shí),默認(rèn)為各個(gè)樣本fold概率分布一致,誤差估計(jì)為所有樣本之和,而非各個(gè)fold的平均。

verbose:日志冗長(zhǎng)度,int:冗長(zhǎng)度,0:不輸出訓(xùn)練過(guò)程,1:偶爾輸出,>1:對(duì)每個(gè)子模型都輸出。

n_jobs: 并行數(shù),int:個(gè)數(shù),-1:跟CPU核數(shù)一致, 1:默認(rèn)值。

pre_dispatch:指定總共分發(fā)的并行任務(wù)數(shù)。當(dāng)n_jobs大于1時(shí),數(shù)據(jù)將在每個(gè)運(yùn)行點(diǎn)進(jìn)行復(fù)制,這可能導(dǎo)致OOM,而設(shè)置pre_dispatch參數(shù),則可以預(yù)先劃分總共的job數(shù)量,使數(shù)據(jù)最多被復(fù)制pre_dispatch次

進(jìn)行預(yù)測(cè)的常用方法和屬性

grid.fit():運(yùn)行網(wǎng)格搜索

grid_scores_:給出不同參數(shù)情況下的評(píng)價(jià)結(jié)果

best_params_:描述了已取得最佳結(jié)果的參數(shù)的組合

best_score_:成員提供優(yōu)化過(guò)程期間觀察到的最好的評(píng)分

model=Lasso()
alpha_can=np.logspace(-3,2,10)
np.set_printoptions(suppress=True)#設(shè)置打印選項(xiàng)
print("alpha_can=",alpha_can)
#cv :交叉驗(yàn)證參數(shù),默認(rèn)None 這里為5折交叉
# param_grid:值為字典或者列表,即需要最優(yōu)化的參數(shù)的取值
lasso_model=GridSearchCV(model,param_grid={'alpha':alpha_can},cv=5)#得到最好的參數(shù)
lasso_model.fit(x_train,y_train)
print('超參數(shù):\n',lasso_model.best_params_)
print("估計(jì)器\n",lasso_model.best_estimator_)

如果有transform,使用Pipeline簡(jiǎn)化系統(tǒng)搭建流程,將transform與分類器串聯(lián)起來(lái)(Pipelineof transforms with a final estimator)

pipeline= Pipeline([("features", combined_features), ("svm", svm)])  
param_grid= dict(features__pca__n_components=[1, 2, 3],  
                  features__univ_select__k=[1,2],  
                  svm__C=[0.1, 1, 10])  
   
grid_search= GridSearchCV(pipeline, param_grid=param_grid, verbose=10)  
grid_search.fit(X,y)  
print(grid_search.best_estimator_) 

8 StandardScaler

作用:去均值和方差歸一化。且是針對(duì)每一個(gè)特征維度來(lái)做的,而不是針對(duì)樣本。

【注意:】
并不是所有的標(biāo)準(zhǔn)化都能給estimator帶來(lái)好處。

# coding=utf-8
# 統(tǒng)計(jì)訓(xùn)練集的 mean 和 std 信息
from sklearn.preprocessing import StandardScaler
import numpy as np
 
 
def test_algorithm():
    np.random.seed(123)
    print('use StandardScaler')
    # 注:shape of data: [n_samples, n_features]
    data = np.random.randn(3, 4)
    scaler = StandardScaler()
    scaler.fit(data)
    trans_data = scaler.transform(data)
    print('original data: ')
    print(data)
    print('transformed data: ')
    print(trans_data)
    print('scaler info: scaler.mean_: {}, scaler.var_: {}'.format(scaler.mean_, scaler.var_))
    print('\n')
 
    print('use numpy by self')
    mean = np.mean(data, axis=0)
    std = np.std(data, axis=0)
    var = std * std
    print('mean: {}, std: {}, var: {}'.format(mean, std, var))
    # numpy 的廣播功能
    another_trans_data = data - mean
    # 注:是除以標(biāo)準(zhǔn)差
    another_trans_data = another_trans_data / std
    print('another_trans_data: ')
    print(another_trans_data)
 
 
if __name__ == '__main__':
    test_algorithm()

運(yùn)行結(jié)果:

9 PolynomialFeatures

使用sklearn.preprocessing.PolynomialFeatures來(lái)進(jìn)行特征的構(gòu)造。

它是使用多項(xiàng)式的方法來(lái)進(jìn)行的,如果有a,b兩個(gè)特征,那么它的2次多項(xiàng)式為(1,a,b,a^2,ab, b^2)。

PolynomialFeatures有三個(gè)參數(shù)

degree:控制多項(xiàng)式的度

interaction_only: 默認(rèn)為False,如果指定為True,那么就不會(huì)有特征自己和自己結(jié)合的項(xiàng),上面的二次項(xiàng)中沒(méi)有a^2和b^2。

include_bias:默認(rèn)為True。如果為True的話,那么就會(huì)有上面的 1那一項(xiàng)。

import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
 
path = r"activity_recognizer\1.csv"
# 數(shù)據(jù)在https://archive.ics.uci.edu/ml/datasets/Activity+Recognition+from+Single+Chest-Mounted+Accelerometer
df = pd.read_csv(path, header=None)
df.columns = ['index', 'x', 'y', 'z', 'activity']
 
knn = KNeighborsClassifier()
knn_params = {'n_neighbors': [3, 4, 5, 6]}
X = df[['x', 'y', 'z']]
y = df['activity']
 
from sklearn.preprocessing import PolynomialFeatures
 
poly = PolynomialFeatures(degree=2, include_bias=False, interaction_only=False)
X_ploly = poly.fit_transform(X)
X_ploly_df = pd.DataFrame(X_ploly, columns=poly.get_feature_names())
print(X_ploly_df.head())

運(yùn)行結(jié)果:

x0 x1 x2 x0^2 x0 x1 x0 x2 x1^2 \
0 1502.0 2215.0 2153.0 2256004.0 3326930.0 3233806.0 4906225.0
1 1667.0 2072.0 2047.0 2778889.0 3454024.0 3412349.0 4293184.0
2 1611.0 1957.0 1906.0 2595321.0 3152727.0 3070566.0 3829849.0
3 1601.0 1939.0 1831.0 2563201.0 3104339.0 2931431.0 3759721.0
4 1643.0 1965.0 1879.0 2699449.0 3228495.0 3087197.0 3861225.0

x1 x2 x2^2
0 4768895.0 4635409.0
1 4241384.0 4190209.0
2 3730042.0 3632836.0
3 3550309.0 3352561.0
4 3692235.0 3530641.0

4、10+款機(jī)器學(xué)習(xí)算法對(duì)比

Sklearn API:http://scikit-learn.org/stable/modules/classes.html#module-sklearn.ensemble

4.1 生成數(shù)據(jù)

import numpy as np
np.random.seed(10)
%matplotlib inline 
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,
                              GradientBoostingClassifier)
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve,accuracy_score,recall_score
from sklearn.pipeline import make_pipeline
from sklearn.calibration import calibration_curve
import copy
print(__doc__)
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
 
# 數(shù)據(jù)
X, y = make_classification(n_samples=100000)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,random_state = 4000)  # 對(duì)半分
X_train, X_train_lr, y_train, y_train_lr = train_test_split(X_train,
                                                            y_train,
                                                            test_size=0.2,random_state = 4000)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
 
def yLabel(y_pred):
    y_pred_f = copy.copy(y_pred)
    y_pred_f[y_pred_f>=0.5] = 1
    y_pred_f[y_pred_f0.5] = 0
    return y_pred_f
 
def acc_recall(y_test, y_pred_rf):
    return {'accuracy': accuracy_score(y_test, yLabel(y_pred_rf)), \

            'recall': recall_score(y_test, yLabel(y_pred_rf))}

4.2 八款主流機(jī)器學(xué)習(xí)模型

h = .02  # step size in the mesh
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM",
         "Decision Tree", "Neural Net", "AdaBoost",
         "Naive Bayes", "QDA"]
# 去掉"Gaussian Process",太耗時(shí),是其他的300倍以上
 
classifiers = [
    KNeighborsClassifier(3),
    SVC(kernel="linear", C=0.025),
    SVC(gamma=2, C=1),
    #GaussianProcessClassifier(1.0 * RBF(1.0)),
    DecisionTreeClassifier(max_depth=5),
    #RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
    MLPClassifier(alpha=1),
    AdaBoostClassifier(),
    GaussianNB(),
    QuadraticDiscriminantAnalysis()]
 
predictEight = {}
for name, clf in zip(names, classifiers):
    predictEight[name] = {}
    predictEight[name]['prob_pos'],predictEight[name]['fpr_tpr'],predictEight[name]['acc_recall'] = [],[],[]
    predictEight[name]['importance'] = []
    print('\n --- Start Model : %s ----\n'%name)
    %time clf.fit(X_train, y_train)
    # 一些計(jì)算決策邊界的模型 計(jì)算decision_function
    if hasattr(clf, "decision_function"):
        %time prob_pos = clf.decision_function(X_test)
        # # The confidence score for a sample is the signed distance of that sample to the hyperplane.
    else:
        %time prob_pos= clf.predict_proba(X_test)[:, 1]
        prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
        # 需要?dú)w一化
    predictEight[name]['prob_pos'] = prob_pos
 
    # 計(jì)算ROC、acc、recall
    predictEight[name]['fpr_tpr'] = roc_curve(y_test, prob_pos)[:2]
    predictEight[name]['acc_recall'] = acc_recall(y_test, prob_pos)  # 計(jì)算準(zhǔn)確率與召回
 
    # 提取信息
    if hasattr(clf, "coef_"):
        predictEight[name]['importance'] = clf.coef_
    elif hasattr(clf, "feature_importances_"):
        predictEight[name]['importance'] = clf.feature_importances_
    elif hasattr(clf, "sigma_"):
        predictEight[name]['importance'] = clf.sigma_
        # variance of each feature per class 在樸素貝葉斯之中體現(xiàn)

結(jié)果輸出類似:

Automatically created module for IPython interactive environment
 
 --- Start Model : Nearest Neighbors ----
 
CPU times: user 103 ms, sys: 0 ns, total: 103 ms
Wall time: 103 ms
CPU times: user 2min 8s, sys: 3.43 ms, total: 2min 8s
Wall time: 2min 9s
 
 --- Start Model : Linear SVM ----
 
CPU times: user 25.4 s, sys: 149 ms, total: 25.6 s
Wall time: 25.6 s
CPU times: user 3.47 s, sys: 1.23 ms, total: 3.47 s
Wall time: 3.47 s

4.3 樹(shù)模型 - 隨機(jī)森林

案例地址:http://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#sphx-glr-auto-examples-ensemble-plot-feature-transformation-py

'''
model 0 : lm
logistic
'''
print('LM 開(kāi)始計(jì)算...')
lm = LogisticRegression()
%time lm.fit(X_train, y_train)
y_pred_lm = lm.predict_proba(X_test)[:, 1]
fpr_lm, tpr_lm, _ = roc_curve(y_test, y_pred_lm)
lm_ar = acc_recall(y_test, y_pred_lm)  # 計(jì)算準(zhǔn)確率與召回
 
'''
model 1 : rt + lm
無(wú)監(jiān)督變換 + lg
'''
# Unsupervised transformation based on totally random trees
print('隨機(jī)森林編碼+LM 開(kāi)始計(jì)算...')
 
 
rt = RandomTreesEmbedding(max_depth=3, n_estimators=n_estimator,
    random_state=0)
# 數(shù)據(jù)集的無(wú)監(jiān)督變換到高維稀疏表示。
 
rt_lm = LogisticRegression()
pipeline = make_pipeline(rt, rt_lm)
%time pipeline.fit(X_train, y_train)
y_pred_rt = pipeline.predict_proba(X_test)[:, 1]
fpr_rt_lm, tpr_rt_lm, _ = roc_curve(y_test, y_pred_rt)
rt_lm_ar = acc_recall(y_test, y_pred_rt)  # 計(jì)算準(zhǔn)確率與召回
 
'''
model 2 : RF / RF+LM
'''
print('\n 隨機(jī)森林系列 開(kāi)始計(jì)算... ')
 
# Supervised transformation based on random forests
rf = RandomForestClassifier(max_depth=3, n_estimators=n_estimator)
rf_enc = OneHotEncoder()
rf_lm = LogisticRegression()
rf.fit(X_train, y_train)
rf_enc.fit(rf.apply(X_train))  # rf.apply(X_train)-(1310, 100)     X_train-(1310, 20)
# 用100棵樹(shù)的信息作為X,載入做LM模型
%time rf_lm.fit(rf_enc.transform(rf.apply(X_train_lr)), y_train_lr)
 
y_pred_rf_lm = rf_lm.predict_proba(rf_enc.transform(rf.apply(X_test)))[:, 1]
fpr_rf_lm, tpr_rf_lm, _ = roc_curve(y_test, y_pred_rf_lm)
rf_lm_ar = acc_recall(y_test, y_pred_rf_lm)  # 計(jì)算準(zhǔn)確率與召回
 
'''
model 2 : GRD / GRD + LM
'''
print('\n 梯度提升樹(shù)系列 開(kāi)始計(jì)算... ')
 
grd = GradientBoostingClassifier(n_estimators=n_estimator)
grd_enc = OneHotEncoder()
grd_lm = LogisticRegression()
grd.fit(X_train, y_train)
grd_enc.fit(grd.apply(X_train)[:, :, 0])
%time grd_lm.fit(grd_enc.transform(grd.apply(X_train_lr)[:, :, 0]), y_train_lr)
 
y_pred_grd_lm = grd_lm.predict_proba(
    grd_enc.transform(grd.apply(X_test)[:, :, 0]))[:, 1]
fpr_grd_lm, tpr_grd_lm, _ = roc_curve(y_test, y_pred_grd_lm)
grd_lm_ar = acc_recall(y_test, y_pred_grd_lm)  # 計(jì)算準(zhǔn)確率與召回
 
# The gradient boosted model by itself
y_pred_grd = grd.predict_proba(X_test)[:, 1]
fpr_grd, tpr_grd, _ = roc_curve(y_test, y_pred_grd)
grd_ar = acc_recall(y_test, y_pred_grd)  # 計(jì)算準(zhǔn)確率與召回
 
 
# The random forest model by itself
y_pred_rf = rf.predict_proba(X_test)[:, 1]
fpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)
rf_ar = acc_recall(y_test, y_pred_rf)  # 計(jì)算準(zhǔn)確率與召回

輸出結(jié)果為:

LM 開(kāi)始計(jì)算...
隨機(jī)森林編碼+LM 開(kāi)始計(jì)算...
CPU times: user 591 ms, sys: 85.5 ms, total: 677 ms
Wall time: 574 ms
 
 隨機(jī)森林系列 開(kāi)始計(jì)算...
CPU times: user 76 ms, sys: 0 ns, total: 76 ms
Wall time: 76 ms
 
 梯度提升樹(shù)系列 開(kāi)始計(jì)算...
CPU times: user 60.6 ms, sys: 0 ns, total: 60.6 ms
Wall time: 60.6 ms

4.4 一些結(jié)果展示:每個(gè)模型的準(zhǔn)確率與召回率

# 8款常規(guī)模型
for x,y in predictEight.items():
    print('\n ----- The Model  : %s , -----\n '%(x)  )
    print(predictEight[x]['acc_recall'])
 
# 樹(shù)模型
names = ['LM','LM + RT','LM + RF','GBT + LM','GBT','RF']
ar_list = [lm_ar,rt_lm_ar,rf_lm_ar,grd_lm_ar,grd_ar,rf_ar]
for x,y in zip(names,ar_list):
    print('\n --- %s 準(zhǔn)確率與召回為: ---- \n '%x,y)

結(jié)果輸出:

 ----- The Model  : Linear SVM , -----
{'recall': 0.84561049445005043, 'accuracy': 0.89100000000000001}
 ---- The Model  : Decision Tree , -----
{'recall': 0.90918264379414737, 'accuracy': 0.89949999999999997}
 ----- The Model  : AdaBoost , -----
{'recall': 0.028254288597376387, 'accuracy': 0.51800000000000002}
 ----- The Model  : Neural Net , -----
{'recall': 0.91523713420787078, 'accuracy': 0.90249999999999997}
 ----- The Model  : Naive Bayes , -----
{'recall': 0.91523713420787078, 'accuracy': 0.89300000000000002}

4.5 結(jié)果展示:校準(zhǔn)曲線

Calibration curves may also be referred to as reliability diagrams.
可靠性檢驗(yàn)的方式。

# #############################################################################
# Plot calibration plots
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM",
         "Decision Tree", "Neural Net", "AdaBoost",
         "Naive Bayes", "QDA"]
 
 
plt.figure(figsize=(15, 15))
ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((3, 1), (2, 0))
 
ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for prob_pos, name in [[predictEight[n]['prob_pos'],n] for n in names] + [(y_pred_lm,'LM'),
                       (y_pred_rt,'RT + LM'),
                       (y_pred_rf_lm,'RF + LM'),
                       (y_pred_grd_lm,'GBT + LM'),
                       (y_pred_grd,'GBT'),
                       (y_pred_rf,'RF')]:
 
    prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
 
    fraction_of_positives, mean_predicted_value = calibration_curve(y_test, prob_pos, n_bins=10)
 
    ax1.plot(mean_predicted_value, fraction_of_positives, "s-",
             label="%s" % (name, ))
 
    ax2.hist(prob_pos, range=(0, 1), bins=10, label=name,
             histtype="step", lw=2)
 
ax1.set_ylabel("Fraction of positives")
ax1.set_ylim([-0.05, 1.05])
ax1.legend(loc="lower right")
ax1.set_title('Calibration plots  (reliability curve)')
 
ax2.set_xlabel("Mean predicted value")
ax2.set_ylabel("Count")
ax2.legend(loc="upper center", ncol=2)
 
plt.tight_layout()
plt.show()

第一張圖
fraction_of_positives,每個(gè)概率片段,正數(shù)的比例= 正數(shù)/總數(shù)
Mean predicted value,每個(gè)概率片段,正數(shù)的平均值
第二張圖
每個(gè)概率分?jǐn)?shù)段的個(gè)數(shù)

結(jié)果展示為:

4.6 模型的結(jié)果展示:重要性輸出

大家都知道一些樹(shù)模型可以輸出重要性,回歸模型可以輸出系數(shù),帶有決策平面的(譬如SVM)可以計(jì)算點(diǎn)到?jīng)Q策邊界的距離。

# 重要性
print('\n -------- RadomFree importances ------------\n')
print(rf.feature_importances_)
print('\n -------- GradientBoosting importances ------------\n')
print(grd.feature_importances_)
print('\n -------- Logistic Coefficient  ------------\n')
lm.coef_ 
# 其他幾款模型的特征選擇
[[predictEight[n]['importance'],n] for n in names if predictEight[n]['importance'] != [] ]

在本次10+機(jī)器學(xué)習(xí)案例之中,可以看到,可以輸出重要性的模型有:
隨機(jī)森林rf.feature_importances_
GBTgrd.feature_importances_
Decision Tree decision.feature_importances_
AdaBoost AdaBoost.feature_importances_

可以計(jì)算系數(shù)的有:線性模型,lm.coef_ 、 SVM svm.coef_

Naive Bayes得到的是:NaiveBayes.sigma_

解釋為:variance of each feature per class

4.7 ROC值的計(jì)算與plot

plt.figure(1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_lm, tpr_lm, label='LR')
plt.plot(fpr_rt_lm, tpr_rt_lm, label='RT + LR')
plt.plot(fpr_rf, tpr_rf, label='RF')
plt.plot(fpr_rf_lm, tpr_rf_lm, label='RF + LR')
plt.plot(fpr_grd, tpr_grd, label='GBT')
plt.plot(fpr_grd_lm, tpr_grd_lm, label='GBT + LR')
# 8 款模型
for (fpr,tpr),name in [[predictEight[n]['fpr_tpr'],n] for n in names] :
    plt.plot(fpr, tpr, label=name)
 
 
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve')
plt.legend(loc='best')
plt.show()
 
plt.figure(2)
plt.xlim(0, 0.2)
plt.ylim(0.4, 1)     # ylim改變     # matt
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_lm, tpr_lm, label='LR')
plt.plot(fpr_rt_lm, tpr_rt_lm, label='RT + LR')
plt.plot(fpr_rf, tpr_rf, label='RF')
plt.plot(fpr_rf_lm, tpr_rf_lm, label='RF + LR')
plt.plot(fpr_grd, tpr_grd, label='GBT')
plt.plot(fpr_grd_lm, tpr_grd_lm, label='GBT + LR')
for (fpr,tpr),name in [[predictEight[n]['fpr_tpr'],n] for n in names] :
    plt.plot(fpr, tpr, label=name)
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve (zoomed in at top left)')
plt.legend(loc='best')
plt.show()

到此這篇關(guān)于一文搞懂Python Sklearn庫(kù)使用方法的文章就介紹到這了,更多相關(guān)Python Sklearn庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python庫(kù)sklearn常用操作
  • Python sklearn庫(kù)實(shí)現(xiàn)PCA教程(以鳶尾花分類為例)
  • python常用庫(kù)之NumPy和sklearn入門
  • Python使用sklearn庫(kù)實(shí)現(xiàn)的各種分類算法簡(jiǎn)單應(yīng)用小結(jié)
  • python sklearn庫(kù)實(shí)現(xiàn)簡(jiǎn)單邏輯回歸的實(shí)例代碼
  • Python基于sklearn庫(kù)的分類算法簡(jiǎn)單應(yīng)用示例

標(biāo)簽:長(zhǎng)治 滄州 河南 新疆 沈陽(yáng) 上海 樂(lè)山 紅河

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《一文搞懂Python Sklearn庫(kù)使用》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    拉孜县| 克东县| 科技| 新沂市| 邵武市| 浠水县| 辉南县| 博野县| 青河县| 英山县| 徐州市| 宁蒗| 桂阳县| 海盐县| 万宁市| 商都县| 渝北区| 塔河县| 永兴县| 桑植县| 永寿县| 成安县| 万荣县| 如东县| 崇义县| 汤阴县| 昌乐县| 荣成市| 洛阳市| 萍乡市| 淳安县| 杨浦区| 清原| 湟中县| 花垣县| 辉县市| 嫩江县| 宁夏| 扬州市| 云阳县| 城固县|