Python之隨機森林實戰

2022-05-06 13:21:12 字數 2214 閱讀 7104

**實現:

1

#-*- coding: utf-8 -*-

2"""

3created on tue sep 4 09:38:57 201845

@author: zhen

6"""78

from sklearn.ensemble import

randomforestclassifier

9from sklearn.model_selection import

train_test_split

10from sklearn.metrics import

accuracy_score

11from sklearn.datasets import

load_iris

12import

matplotlib.pyplot as plt

1314 iris =load_iris()

15 x = iris.data[:, :2]

16 y =iris.target

17 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)

1819

#n_estimators:森林中樹的個數(預設為10),建議為奇數20#

n_jobs:並行執行任務的個數(包括模型訓練和**),預設值為-1,表示根據核數

21 rnd_clf = randomforestclassifier(n_estimators=15, max_leaf_nodes=16, n_jobs=1)

22 rnd_clf.fit(x_train, y_train)

23 24 y_predict_rf = rnd_clf.predict(x_test)

2526

print

(accuracy_score(y_test, y_predict_rf))

2728

for name, score in zip(iris['

feature_names

'], rnd_clf.feature_importances_):

29print

(name, score)

3031

#視覺化

32 plt.plot(x_test[:, 0], y_test, '

r.', label='

real')

33 plt.plot(x_test[:, 0], y_predict_rf, '

b.', label='

predict')

34 plt.xlabel('

sepal-length

', fontsize=15)

35 plt.ylabel('

type

', fontsize=15)

36 plt.legend(loc="

upper left")

37plt.show()

3839 plt.plot(x_test[:, 1], y_test, '

r.', label='

real')

40 plt.plot(x_test[:, 1], y_predict_rf, '

b.', label='

predict')

41 plt.xlabel('

sepal-width

', fontsize=15)

42 plt.ylabel('

type

', fontsize=15)

43 plt.legend(loc="

upper right")

44 plt.show()

結果:

視覺化(檢視每個**條件的影響):

分析:鳶尾花的花萼長度在小於6時**準確率很高,隨著長度的增加,在6~7這段中,**出現較大錯誤率,當大於7時,**會恢復到較好的情況。寬度也出現類似的情況,在3~3.5這個範圍出現較高錯誤,因此在訓練中建議在訓練資料中適量增加中間部分資料的訓練量(該部分不容易區分),以便得到較好的訓練模型!

隨機森林 python

這 幾天一直在看隨機森林。可以說遇到任何乙個有關 的問題。都可以首先隨機森林來進行 同時得到的結果也不會太差。在這篇文章裡我首先會向大家推薦幾篇寫的比較好的部落格。接著會將我覺得比較好的例子使用python scikit learn包來實現出來。首先推薦的就是 隨機森林入門 簡化版 老外寫的部落格,...

Python 隨機森林

隨機森林講解文件 scikit learn官方文件 scikit learn的官方文件 主要告訴大家如何使用scikit learn包中的類方法來進行隨機森林演算法的 其中講的比較好的是各個引數的具體用途。這裡我給出我的理解和部分翻譯 1 sklearn ensemble模組包含了兩個基於隨機決策樹...

Python資料探勘之隨機森林

主要是使用隨機森林將four列缺失的資料補齊。fit到randomforestregressor之中,n estimators代表隨機森林中的決策樹數量 n jobs這個引數告訴引擎有多少處理器是它可以使用。1 意味著沒有限制,而 1 值意味著它只能使用乙個處理器。import pandas as ...