開始使用免費開始

擷取隨機森林的參數

現在你要把先前在羅吉斯回歸模型上的作法,轉換到隨機森林模型。這個模型的一個參數是:對於每一棵樹,它在各層級如何決定分裂。

這樣的分析不像羅吉斯回歸的係數那麼實用,因為你幾乎不可能去逐一檢視隨機森林中每一次分裂與每一棵樹。不過,做這個練習可以讓你一窺模型內部的運作,仍然很有幫助。

在本練習中,我們會從隨機森林模型中擷取單一一棵樹,將它視覺化,並以程式方式擷取其中一個分裂。

你手上已有:

  • 一個隨機森林模型物件 rf_clf
  • 所選決策樹頂部的影像 tree_viz_image
  • X_train DataFrame 與 original_variables 清單

本練習屬於課程

Python 超參數調校

檢視課程

練習說明

  • 從隨機森林模型中擷取第 7 棵樹(索引為 6)。
  • 視覺化這棵樹(tree_viz_image),查看其分裂決策。
  • 擷取最上層分裂的特徵與門檻(level)。
  • 將特徵與門檻一起印出。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Extract the 7th (index 6) tree from the random forest
chosen_tree = rf_clf.estimators_[____]

# Visualize the graph using the provided image
imgplot = plt.imshow(____)
plt.show()

# Extract the parameters and level of the top (index 0) node
split_column = chosen_tree.tree_.feature[____]
split_column_name = X_train.columns[split_column]
split_value = chosen_tree.tree_.threshold[____]

# Print out the feature and level
print("This node split on feature {}, at a value of {}".format(split_column_name, ____))
編輯並執行程式碼