自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

機器學習第一步,這是一篇手把手的隨機森林入門實戰(zhàn)

新聞 機器學習
到了 2020 年,我們已經(jīng)能找到很多好玩的機器學習教程。本文則從最流行的隨機森林出發(fā),手把手教你構(gòu)建一個模型,它的完整流程到底是什么樣的。

 到了 2020 年,我們已經(jīng)能找到很多好玩的機器學習教程。本文則從最流行的隨機森林出發(fā),手把手教你構(gòu)建一個模型,它的完整流程到底是什么樣的。

机器学习第一步,这是一篇手把手的随机森林入门实战

作為數(shù)據(jù)科學家,我們可以通過很多方法來創(chuàng)建分類模型。最受歡迎的方法之一是隨機森林。我們可以在隨機森林上調(diào)整超參數(shù)來優(yōu)化模型的性能。

在用模型擬合之前,嘗試主成分分析(PCA)也是常見的做法。但是,為什么還要增加這一步呢?難道隨機森林的目的不是幫助我們更輕松地理解特征重要性嗎?

當我們分析隨機森林模型的「特征重要性」時,PCA 會使每個「特征」的解釋變得更加困難。但是 PCA 會進行降維操作,這可以減少隨機森林要處理的特征數(shù)量,因此 PCA 可能有助于加快隨機森林模型的訓練速度。

請注意,計算成本高是隨機森林的最大缺點之一(運行模型可能需要很長時間)。尤其是當你使用數(shù)百甚至上千個預測特征時,PCA 就變得非常重要。因此,如果只想簡單地擁有最佳性能的模型,并且可以犧牲解釋特征的重要性,那么 PCA 可能會很有用。

現(xiàn)在讓我們舉個例子。我們將使用 Scikit-learn 的「乳腺癌」數(shù)據(jù)集,并創(chuàng)建 3 個模型,比較它們的性能:

 1. 隨機森林

2. 具有 PCA 降維的隨機森林

3. 具有 PCA 降維和超參數(shù)調(diào)整的隨機森林

導入數(shù)據(jù)

首先,我們加載數(shù)據(jù)并創(chuàng)建一個 DataFrame。這是 Scikit-learn 預先清理的「toy」數(shù)據(jù)集,因此我們可以繼續(xù)快速建模。但是,作為最佳實踐,我們應該執(zhí)行以下操作:

  • 使用 df.head()查看新的 DataFrame,以確保它符合預期。
  • 使用 df.info()可以了解每一列中的數(shù)據(jù)類型和數(shù)據(jù)量。可能需要根據(jù)需要轉(zhuǎn)換數(shù)據(jù)類型。
  • 使用 df.isna()確保沒有 NaN 值。可能需要根據(jù)需要處理缺失值或刪除行。
  • 使用 df.describe()可以了解每列的最小值、最大值、均值、中位數(shù)、標準差和四分位數(shù)范圍。

名為「cancer」的列是我們要使用模型預測的目標變量?!?」表示「無癌癥」,「1」表示「癌癥」。

  1. import pandas as pd 
  2. from sklearn.datasets import load_breast_cancercolumns = ['mean radius''mean texture''mean perimeter''mean area''mean smoothness''mean compactness''mean concavity''mean concave points''mean symmetry''mean fractal dimension''radius error''texture error''perimeter error''area error''smoothness error''compactness error''concavity error''concave points error''symmetry error''fractal dimension error''worst radius''worst texture''worst perimeter''worst area''worst smoothness''worst compactness''worst concavity''worst concave points''worst symmetry''worst fractal dimension']dataset = load_breast_cancer() 
  3. data = pd.DataFrame(dataset['data'], columns=columns) 
  4. data['cancer'] = dataset['target']display(data.head()) 
  5. display(data.info()) 
  6. display(data.isna().sum()) 
  7. display(data.describe()) 

机器学习第一步,这是一篇手把手的随机森林入门实战

上圖是乳腺癌 DataFrame 的一部分。每行是一個患者的觀察結(jié)果。最后一列名為「cancer」是我們要預測的目標變量。0 表示「無癌癥」,1 表示「癌癥」。

訓練集/測試集分割

現(xiàn)在,我們使用 Scikit-learn 的「train_test_split」函數(shù)拆分數(shù)據(jù)。我們想讓模型有盡可能多的數(shù)據(jù)進行訓練。但是,我們也要確保有足夠的數(shù)據(jù)來測試模型。通常數(shù)據(jù)集中行數(shù)越多,我們可以提供給訓練集的數(shù)據(jù)越多。

例如,如果我們有數(shù)百萬行,那么我們可以將其中的 90%用作訓練,10%用作測試。但是,我們的數(shù)據(jù)集只有 569 行,數(shù)據(jù)量并不大。因此,為了匹配這種小型數(shù)據(jù)集,我們會將數(shù)據(jù)分為 50%的訓練和 50%的測試。我們設(shè)置 stratify = y 以確保訓練集和測試集與原始數(shù)據(jù)集的 0 和 1 的比例一致。

  1. from sklearn.model_selection import train_test_splitX = data.drop('cancer', axis=1)   
  2. y = data['cancer']  
  3. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.50, random_state = 2020, stratify=y) 

規(guī)范化數(shù)據(jù)

在建模之前,我們需要先將數(shù)據(jù)「居中」和「標準化」,對不同的變量要在相同尺度進行測量。我們進行縮放以便決定預測變量的特征可以彼此「公平競爭」。我們還將「y_train」從 Pandas「Series」對象轉(zhuǎn)換為 NumPy 數(shù)組,以供模型稍后接收訓練數(shù)據(jù)。

  1. import numpy as np 
  2. from sklearn.preprocessing import StandardScalerss = StandardScaler() 
  3. X_train_scaled = ss.fit_transform(X_train) 
  4. X_test_scaled = ss.transform(X_test) 
  5. y_train = np.array(y_train) 

擬合「基線」隨機森林模型

現(xiàn)在,我們創(chuàng)建一個「基線」隨機森林模型。該模型使用 Scikit-learn 隨機森林分類器文檔中定義的所有預測特征和默認設(shè)置。首先,我們實例化模型并使用規(guī)范化的數(shù)據(jù)擬合模型。我們可以通過訓練數(shù)據(jù)測量模型的準確性。

  1. from sklearn.ensemble import RandomForestClassifier 
  2. from sklearn.metrics import recall_scorerfc = RandomForestClassifier() 
  3. rfc.fit(X_train_scaled, y_train) 
  4. display(rfc.score(X_train_scaled, y_train))# 1.0 

如果我們想知道哪些特征對隨機森林模型預測乳腺癌最重要,我們可以通過調(diào)用「feature_importances _」方法來可視化和量化這些重要特征:

  1. feats = {} 
  2. for feature, importance in zip(data.columns, rfc_1.feature_importances_): 
  3. feats[feature] = importanceimportances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0'Gini-Importance'}) 
  4. importances = importances.sort_values(by='Gini-Importance', ascending=False) 
  5. importances = importances.reset_index() 
  6. importances = importances.rename(columns={'index''Features'})sns.set(font_scale = 5
  7. sns.set(style="whitegrid", color_codes=True, font_scale = 1.7
  8. fig, ax = plt.subplots() 
  9. fig.set_size_inches(30,15
  10. sns.barplot(x=importances['Gini-Importance'], y=importances['Features'], data=importances, color='skyblue'
  11. plt.xlabel('Importance', fontsize=25, weight = 'bold'
  12. plt.ylabel('Features', fontsize=25, weight = 'bold'
  13. plt.title('Feature Importance', fontsize=25, weight = 'bold')display(plt.show()) 
  14. display(importances) 

机器学习第一步,这是一篇手把手的随机森林入门实战

机器学习第一步,这是一篇手把手的随机森林入门实战

主成分分析(PCA)

現(xiàn)在,我們?nèi)绾胃倪M基線模型呢?使用降維,我們可以用更少的變量來擬合原始數(shù)據(jù)集,同時降低運行模型的計算花銷。使用 PCA,我們可以研究這些特征的累積方差比,以了解哪些特征代表數(shù)據(jù)中的最大方差。

我們實例化 PCA 函數(shù)并設(shè)置我們要考慮的成分(特征)數(shù)量。此處我們設(shè)置為 30,以查看所有生成成分的方差,并決定在何處切割。然后,我們將縮放后的 X_train 數(shù)據(jù)「擬合」到 PCA 函數(shù)中。

  1. import matplotlib.pyplot as plt 
  2. import seaborn as sns 
  3. from sklearn.decomposition import PCApca_test = PCA(n_components=30
  4. pca_test.fit(X_train_scaled)sns.set(style='whitegrid'
  5. plt.plot(np.cumsum(pca_test.explained_variance_ratio_)) 
  6. plt.xlabel('number of components'
  7. plt.ylabel('cumulative explained variance'
  8. plt.axvline(linewidth=4, color='r', linestyle = '--', x=10, ymin=0, ymax=1
  9. display(plt.show())evr = pca_test.explained_variance_ratio_ 
  10. cvr = np.cumsum(pca_test.explained_variance_ratio_)pca_df = pd.DataFrame() 
  11. pca_df['Cumulative Variance Ratio'] = cvr 
  12. pca_df['Explained Variance Ratio'] = evr 
  13. display(pca_df.head(10)) 

机器学习第一步,这是一篇手把手的随机森林入门实战

該圖顯示,在超過 10 個特征之后,我們并未獲得太多的解釋方差。此 DataFrame 顯示了累積方差比(解釋了數(shù)據(jù)的總方差)和解釋方差比(每個 PCA 成分說明了多少數(shù)據(jù)的總方差)。

机器学习第一步,这是一篇手把手的随机森林入门实战

從上面的 DataFrame 可以看出,當我們使用 PCA 將 30 個預測變量減少到 10 個分量時,我們?nèi)匀豢梢越忉?95%以上的方差。其他 20 個分量僅解釋了不到 5%的方差,因此 我們可以減少他們的權(quán)重。按此邏輯,我們將使用 PCA 將 X_train 和 X_test 的成分數(shù)量從 30 個減少到 10 個。我們將這些重新創(chuàng)建的「降維」數(shù)據(jù)集分配給「X_train_scaled_pca」和「X_test_scaled_pca」。

  1. pca = PCA(n_components=10
  2. pca.fit(X_train_scaled)X_train_scaled_pca = pca.transform(X_train_scaled) 
  3. X_test_scaled_pca = pca.transform(X_test_scaled) 

每個分量都是原始變量和相應「權(quán)重」的線性組合。通過創(chuàng)建一個 DataFrame,我們可以看到每個 PCA 成分的「權(quán)重」。

  1. pca_dims = [] 
  2. for x in range(0, len(pca_df)): 
  3. pca_dims.append('PCA Component {}'.format(x))pca_test_df = pd.DataFrame(pca_test.components_, columns=columns, index=pca_dims) 
  4. pca_test_df.head(10).T 

机器学习第一步,这是一篇手把手的随机森林入门实战

PCA 后擬合「基線」隨機森林模型

現(xiàn)在,我們可以將 X_train_scaled_pca 和 y_train 數(shù)據(jù)擬合到另一個「基線」隨機森林模型中,測試我們對該模型的預測是否有所改進。

  1. rfc = RandomForestClassifier() 
  2. rfc.fit(X_train_scaled_pca, y_train)display(rfc.score(X_train_scaled_pca, y_train))# 1.0 

第 1 輪超參數(shù)調(diào)優(yōu):RandomSearchCV

實現(xiàn) PCA 之后,我們還可以通過一些超參數(shù)調(diào)優(yōu)來調(diào)整我們的隨機森林以獲得更好的預測效果。超參數(shù)可以看作模型的「設(shè)置」。兩個不同數(shù)據(jù)集的理想設(shè)置并不相同,因此我們必須「調(diào)整」模型。

首先,我們可以從 RandomSearchCV 開始考慮更多的超參值。所有隨機森林的超參數(shù)都可以在 Scikit-learn 隨機森林分類器文檔中找到。

我們生成一個「param_dist」,其值的范圍適用于每個超參數(shù)。實例化 RandomSearchCV,首先傳入我們的隨機森林模型,然后傳入「param_dist」、測試迭代次數(shù)以及交叉驗證次數(shù)。

超參數(shù)「n_jobs」可以決定要使用多少處理器內(nèi)核來運行模型。設(shè)置「n_jobs = -1」將使模型運行最快,因為它使用了所有計算機核心。

我們將調(diào)整這些超參數(shù):

  • n_estimators:隨機森林中「樹」的數(shù)量。
  • max_features:每個分割處的特征數(shù)。
  • max_depth:每棵樹可以擁有的最大「分裂」數(shù)。
  • min_samples_split:在樹的節(jié)點分裂前所需的最少觀察數(shù)。
  • min_samples_leaf:每棵樹末端的葉節(jié)點所需的最少觀察數(shù)。
  • bootstrap:是否使用 bootstrapping 來為隨機林中的每棵樹提供數(shù)據(jù)。(bootstrapping 是從數(shù)據(jù)集中進行替換的隨機抽樣。)
  1. from sklearn.model_selection import RandomizedSearchCVn_estimators = [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)]max_features = ['log2''sqrt']max_depth = [int(x) for x in np.linspace(start = 1, stop = 15, num = 15)]min_samples_split = [int(x) for x in np.linspace(start = 2, stop = 50, num = 10)]min_samples_leaf = [int(x) for x in np.linspace(start = 2, stop = 50, num = 10)]bootstrap = [True, False]param_dist = {'n_estimators': n_estimators, 
  2. 'max_features': max_features, 
  3. 'max_depth': max_depth, 
  4. 'min_samples_split': min_samples_split, 
  5. 'min_samples_leaf': min_samples_leaf, 
  6. 'bootstrap': bootstrap}rs = RandomizedSearchCV(rfc_2,  
  7. param_dist,  
  8. n_iter = 100,  
  9. cv = 3,  
  10. verbose = 1,  
  11. n_jobs=-1,  
  12. random_state=0)rs.fit(X_train_scaled_pca, y_train) 
  13. rs.best_params_ 
  14.  
  15. ———————————————————————————————————————————— 
  16. # {'n_estimators'700
  17. 'min_samples_split'2
  18. 'min_samples_leaf'2
  19. 'max_features''log2'
  20. 'max_depth'11
  21. 'bootstrap': True} 

在 n_iter = 100 且 cv = 3 的情況下,我們創(chuàng)建了 300 個隨機森林模型,對上面輸入的超參數(shù)進行隨機采樣組合。我們可以調(diào)用「best_params」以獲取性能最佳的模型參數(shù)(如上面代碼框底部所示)。

但是,現(xiàn)階段的「best_params」可能無法為我們提供最有效的信息,以獲取一系列參數(shù)來執(zhí)行下一次超參數(shù)調(diào)整。為了在更大范圍內(nèi)進行嘗試,我們可以輕松地獲得 RandomSearchCV 結(jié)果的 DataFrame。

  1. rs_df = pd.DataFrame(rs.cv_results_).sort_values('rank_test_score').reset_index(drop=True) 
  2. rs_df = rs_df.drop([ 
  3. 'mean_fit_time',  
  4. 'std_fit_time',  
  5. 'mean_score_time'
  6. 'std_score_time',  
  7. 'params',  
  8. 'split0_test_score',  
  9. 'split1_test_score',  
  10. 'split2_test_score',  
  11. 'std_test_score'], 
  12. axis=1
  13. rs_df.head(10

机器学习第一步,这是一篇手把手的随机森林入门实战

現(xiàn)在,讓我們在 x 軸上創(chuàng)建每個超參數(shù)的柱狀圖,并針對每個值制作模型的平均得分,查看平均而言最優(yōu)的值:

  1. fig, axs = plt.subplots(ncols=3, nrows=2
  2. sns.set(style="whitegrid", color_codes=True, font_scale = 2
  3. fig.set_size_inches(30,25)sns.barplot(x='param_n_estimators', y='mean_test_score', data=rs_df, ax=axs[0,0], color='lightgrey'
  4. axs[0,0].set_ylim([.83,.93])axs[0,0].set_title(label = 'n_estimators', size=30, weight='bold')sns.barplot(x='param_min_samples_split', y='mean_test_score', data=rs_df, ax=axs[0,1], color='coral'
  5. axs[0,1].set_ylim([.85,.93])axs[0,1].set_title(label = 'min_samples_split', size=30, weight='bold')sns.barplot(x='param_min_samples_leaf', y='mean_test_score', data=rs_df, ax=axs[0,2], color='lightgreen'
  6. axs[0,2].set_ylim([.80,.93])axs[0,2].set_title(label = 'min_samples_leaf', size=30, weight='bold')sns.barplot(x='param_max_features', y='mean_test_score', data=rs_df, ax=axs[1,0], color='wheat'
  7. axs[1,0].set_ylim([.88,.92])axs[1,0].set_title(label = 'max_features', size=30, weight='bold')sns.barplot(x='param_max_depth', y='mean_test_score', data=rs_df, ax=axs[1,1], color='lightpink'
  8. axs[1,1].set_ylim([.80,.93])axs[1,1].set_title(label = 'max_depth', size=30, weight='bold')sns.barplot(x='param_bootstrap',y='mean_test_score', data=rs_df, ax=axs[1,2], color='skyblue'
  9. axs[1,2].set_ylim([.88,.92]) 

机器学习第一步,这是一篇手把手的随机森林入门实战

通過上面的圖,我們可以了解每個超參數(shù)的值的平均執(zhí)行情況。

n_estimators:300、500、700 的平均分數(shù)幾乎最高;

min_samples_split:較小的值(如 2 和 7)得分較高。23 處得分也很高。我們可以嘗試一些大于 2 的值,以及 23 附近的值;

min_samples_leaf:較小的值可能得到更高的分,我們可以嘗試使用 2–7 之間的值;

max_features:「sqrt」具有最高平均分;

max_depth:沒有明確的結(jié)果,但是 2、3、7、11、15 的效果很好;

bootstrap:「False」具有最高平均分。

現(xiàn)在我們可以利用這些結(jié)論,進入第二輪超參數(shù)調(diào)整,以進一步縮小選擇范圍。

第 2 輪超參數(shù)調(diào)整:GridSearchCV

使用 RandomSearchCV 之后,我們可以使用 GridSearchCV 對目前最佳超參數(shù)執(zhí)行更精細的搜索。超參數(shù)是相同的,但是現(xiàn)在我們使用 GridSearchCV 執(zhí)行更「詳盡」的搜索。

在 GridSearchCV 中,我們嘗試每個超參數(shù)的單獨組合,這比 RandomSearchCV 所需的計算力要多得多,在這里我們可以直接控制要嘗試的迭代次數(shù)。例如,僅對 6 個參數(shù)搜索 10 個不同的參數(shù)值,具有 3 折交叉驗證,則需要擬合模型 3,000,000 次!這就是為什么我們在使用 RandomSearchCV 之后執(zhí)行 GridSearchCV,這能幫助我們首先縮小搜索范圍。

因此,利用我們從 RandomizedSearchCV 中學到的知識,代入每個超參數(shù)的平均最佳執(zhí)行范圍:

  1. from sklearn.model_selection import GridSearchCVn_estimators = [300,500,700
  2. max_features = ['sqrt'
  3. max_depth = [2,3,7,11,15
  4. min_samples_split = [2,3,4,22,23,24
  5. min_samples_leaf = [2,3,4,5,6,7
  6. bootstrap = [False]param_grid = {'n_estimators': n_estimators, 
  7. 'max_features': max_features, 
  8. 'max_depth': max_depth, 
  9. 'min_samples_split': min_samples_split, 
  10. 'min_samples_leaf': min_samples_leaf, 
  11. 'bootstrap': bootstrap}gs = GridSearchCV(rfc_2, param_grid, cv = 3, verbose = 1, n_jobs=-1
  12. gs.fit(X_train_scaled_pca, y_train) 
  13. rfc_3 = gs.best_estimator_ 
  14. gs.best_params_ 
  15.  
  16. ———————————————————————————————————————————— 
  17. # {'bootstrap': False, 
  18. 'max_depth'7
  19. 'max_features''sqrt'
  20. 'min_samples_leaf'3
  21. 'min_samples_split'2
  22. 'n_estimators'500

在這里我們將對 3x 1 x 5x 6 x 6 x 1 = 540 個模型進行 3 折交叉驗證,總共是 1,620 個模型!現(xiàn)在,在執(zhí)行 RandomizedSearchCV 和 GridSearchCV 之后,我們 可以調(diào)用「best_params_」獲得一個最佳模型來預測我們的數(shù)據(jù)(如上面代碼框的底部所示)。

根據(jù)測試數(shù)據(jù)評估模型的性能

現(xiàn)在,我們可以在測試數(shù)據(jù)上評估我們建立的模型。我們會測試 3 個模型:

  • 基線隨機森林
  • 具有 PCA 降維的基線隨機森林
  • 具有 PCA 降維和超參數(shù)調(diào)優(yōu)的基線隨機森林

讓我們?yōu)槊總€模型生成預測結(jié)果:

  1. y_pred = rfc.predict(X_test_scaled) 
  2. y_pred_pca = rfc.predict(X_test_scaled_pca) 
  3. y_pred_gs = gs.best_estimator_.predict(X_test_scaled_pca) 

然后,我們?yōu)槊總€模型創(chuàng)建混淆矩陣,查看每個模型對乳腺癌的預測能力:

  1. from sklearn.metrics import confusion_matrixconf_matrix_baseline = pd.DataFrame(confusion_matrix(y_test, y_pred), index = ['actual 0''actual 1'], columns = ['predicted 0''predicted 1'])conf_matrix_baseline_pca = pd.DataFrame(confusion_matrix(y_test, y_pred_pca), index = ['actual 0''actual 1'], columns = ['predicted 0''predicted 1'])conf_matrix_tuned_pca = pd.DataFrame(confusion_matrix(y_test, y_pred_gs), index = ['actual 0''actual 1'], columns = ['predicted 0''predicted 1'])display(conf_matrix_baseline) 
  2. display('Baseline Random Forest recall score', recall_score(y_test, y_pred)) 
  3. display(conf_matrix_baseline_pca) 
  4. display('Baseline Random Forest With PCA recall score', recall_score(y_test, y_pred_pca)) 
  5. display(conf_matrix_tuned_pca) 
  6. display('Hyperparameter Tuned Random Forest With PCA Reduced Dimensionality recall score', recall_score(y_test, y_pred_gs)) 

下面是預測結(jié)果:

机器学习第一步,这是一篇手把手的随机森林入门实战

我們將召回率作為性能指標,因為我們處理的是癌癥診斷,我們最關(guān)心的是將模型中的假陰性預測誤差最小。

考慮到這一點,看起來我們的基線隨機森林模型表現(xiàn)最好,召回得分為 94.97%。根據(jù)我們的測試數(shù)據(jù)集,基線模型可以正確預測 179 名癌癥患者中的 170 名。

這個案例研究提出了一個重要的注意事項:有時,在 PCA 之后,甚至在進行大量的超參數(shù)調(diào)整之后,調(diào)整的模型性能可能不如普通的「原始」模型。但是嘗試很重要,你不嘗試,就永遠都不知道哪種模型最好。在預測癌癥方面,模型越好,可以挽救的生命就更多。

 

 

責任編輯:張燕妮 來源: 機器之心
相關(guān)推薦

2019-11-21 15:35:28

機器學習人工智能計算機

2009-01-18 08:49:04

Java入門JDK

2021-08-24 05:07:25

React

2021-01-15 18:17:06

網(wǎng)絡(luò)協(xié)議分層

2018-02-10 11:24:39

Python數(shù)據(jù)程序

2010-01-21 10:29:54

java認證

2015-06-02 11:42:00

Cloud FoundAzure

2012-07-11 16:43:14

飛視美

2013-01-15 09:17:11

2019-11-20 10:54:46

無密碼身份驗證網(wǎng)絡(luò)安全

2017-08-28 16:09:13

機器學習自動化Hyperopt

2010-07-01 13:44:12

2011-07-25 14:17:46

BSMIT運維北塔

2012-08-30 11:14:11

云計算虛擬化

2020-07-22 22:10:34

互聯(lián)網(wǎng)物聯(lián)網(wǎng)IOT

2020-11-17 14:55:36

亞馬遜云科技遷移

2023-06-09 11:33:42

數(shù)據(jù)分析報告

2022-09-21 11:29:05

數(shù)據(jù)分析業(yè)務(wù)復盤

2020-11-11 07:09:05

隔離直播系統(tǒng)

2013-04-03 09:22:14

虛擬化網(wǎng)絡(luò)虛擬化
點贊
收藏

51CTO技術(shù)棧公眾號