隨機(jī)森林是一種監(jiān)督學(xué)習(xí)算法,可用于分類和回歸,但是,它主要用于分類問題,眾所周知,森林由樹木組成,更多樹木意味著更堅固的森林。同樣,隨機(jī)森林算法在數(shù)據(jù)樣本上創(chuàng)建決策樹,然后從每個樣本中獲取預(yù)測,最后通過投票選擇最佳解決方案。它是一種集成方法,比單個決策樹要好,因?yàn)樗梢酝ㄟ^對輸出求平均值來減少過度擬合。
隨機(jī)森林算法
無涯教程可以通過以下步驟來了解隨機(jī)森林算法的工作原理-
步驟1? ?-? 首先,從給定的數(shù)據(jù)集中選擇隨機(jī)樣本。
步驟2? ?-? 接下來,該算法將為每個樣本構(gòu)造一個決策樹。然后它將從每個決策樹中獲得預(yù)測輸出。
步驟3? ?-? 在此步驟中,將對每個預(yù)測輸出進(jìn)行投票。
步驟4? ?-? 最后,選擇投票最多的預(yù)測輸出作為最終預(yù)測輸出。??
下圖將說明其工作方式-
代碼實(shí)現(xiàn)
首先,從導(dǎo)入必要的Python包開始-
import numpy as np import matplotlib.pyplot as plt import pandas as pd
接下來,如下所示從其網(wǎng)絡(luò)鏈接下載iris數(shù)據(jù)集:
path="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
接下來,需要為數(shù)據(jù)集分配列名稱,如下所示:
headernames=[sepal-length, sepal-width, petal-length, petal-width, Class]
現(xiàn)在,需要將數(shù)據(jù)集讀取為pandas數(shù)據(jù)框,如下所示:
dataset=pd.read_csv(path, names=headernames) dataset.head()
分隔長度 | 分隔寬度 | 花瓣長度 | 花瓣寬度 | 類 | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | Iris-setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | Iris-setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | Iris-setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | Iris-setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | Iris-setosa |
數(shù)據(jù)預(yù)處理將在以下腳本行的幫助下完成。
X=dataset.iloc[:, :-1].values y=dataset.iloc[:, 4].values
接下來,無涯教程將數(shù)據(jù)分為訓(xùn)練和測試拆分。以下代碼將數(shù)據(jù)集分為70%的訓(xùn)練數(shù)據(jù)和30%的測試數(shù)據(jù)-
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test=train_test_split(X, y, test_size=0.30)
接下來,借助sklearn的 RandomForestClassifier 類訓(xùn)練模型,如下所示:
from sklearn.ensemble import RandomForestClassifier classifier=RandomForestClassifier(n_estimators=50) classifier.fit(X_train, y_train)
最后,需要進(jìn)行預(yù)測??梢栽谝韵履_本的幫助下完成-
y_pred=classifier.predict(X_test)
接下來,按如下所示打印輸出-
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score result = confusion_matrix(y_test, y_pred) print("Confusion Matrix:") print(result) result1 = classification_report(y_test, y_pred) print("Classification Report:",) print (result1) result2 = accuracy_score(y_test,y_pred) print("Accuracy:",result2)
運(yùn)行上面代碼輸出文章來源:http://www.zghlxwxcb.cn/news/detail-677028.html
Confusion Matrix: [[14 0 0] [ 0 18 1] [ 0 0 12]] Classification Report: precision recall f1-score support Iris-setosa 1.00 1.00 1.00 14 Iris-versicolor 1.00 0.95 0.97 19 Iris-virginica 0.92 1.00 0.96 12 micro avg 0.98 0.98 0.98 45 macro avg 0.97 0.98 0.98 45 weighted avg 0.98 0.98 0.98 45 Accuracy: 0.9777777777777777
分類算法 - 隨機(jī)森林 - 無涯教程網(wǎng)無涯教程網(wǎng)提供隨機(jī)森林是一種監(jiān)督學(xué)習(xí)算法,可用于分類和回歸,但是,它主要用于分類問題,眾所周知...https://www.learnfk.com/python-machine-learning/machine-learning-with-python-classification-algorithms-random-forest.html文章來源地址http://www.zghlxwxcb.cn/news/detail-677028.html
到了這里,關(guān)于無涯教程-分類算法 - 隨機(jī)森林的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!