AI人工智能 隨機(jī)森林分類器

2020-09-23 15:37 更新

集成方法是將機(jī)器學(xué)習(xí)模型組合成更強(qiáng)大的機(jī)器學(xué)習(xí)模型的方法。 隨機(jī)森林是決策樹(shù)的集合,就是其中之一。 它比單一決策樹(shù)好,因?yàn)樵诒A纛A(yù)測(cè)能力的同時(shí),通過(guò)平均結(jié)果可以減少過(guò)度擬合。 在這里,我們將在 scikit 學(xué)習(xí)癌癥數(shù)據(jù)集上實(shí)施隨機(jī)森林模型。

導(dǎo)入必要的軟件包 -

  1. from sklearn.ensemble import RandomForestClassifier
  2. from sklearn.model_selection import train_test_split
  3. from sklearn.datasets import load_breast_cancer
  4. cancer = load_breast_cancer()
  5. import matplotlib.pyplot as plt
  6. import numpy as np

現(xiàn)在,需要按照以下方式提供數(shù)據(jù)集

  1. cancer = load_breast_cancer()
  2. X_train, X_test, y_train,
  3. y_test = train_test_split(cancer.data, cancer.target, random_state = 0)

在提供數(shù)據(jù)集之后,需要擬合可以如下完成的模型 -

  1. forest = RandomForestClassifier(n_estimators = 50, random_state = 0)
  2. forest.fit(X_train,y_train)

現(xiàn)在,獲得訓(xùn)練以及測(cè)試子集的準(zhǔn)確性:如果增加估計(jì)器的數(shù)量,那么測(cè)試子集的準(zhǔn)確性也會(huì)增加。

  1. print('Accuracy on the training subset:(:.3f)',format(forest.score(X_train,y_train)))
  2. print('Accuracy on the training subset:(:.3f)',format(forest.score(X_test,y_test)))

上面代碼,輸出結(jié)果如下所示 -

  1. Accuracy on the training subset:(:.3f) 1.0
  2. Accuracy on the training subset:(:.3f) 0.965034965034965

現(xiàn)在,與決策樹(shù)一樣,隨機(jī)森林具有 feature_importance 模塊,它將提供比決策樹(shù)更好的特征權(quán)重視圖。 它可以如下繪制和可視化 -

  1. n_features = cancer.data.shape[1]
  2. plt.barh(range(n_features),forest.feature_importances_, align='center')
  3. plt.yticks(np.arange(n_features),cancer.feature_names)
  4. plt.xlabel('Feature Importance')
  5. plt.ylabel('Feature')
  6. plt.show()

執(zhí)行上面代碼,得到以下輸出結(jié)果 -

img

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)