開始使用免費開始

調整 Random Forest 以進行詐欺偵測

在這個練習中,你會深入了解隨機森林分類器的各種選項,包含設定權重與微調森林中決策樹的結構。你會手動定義權重,以稍微平衡類別不均。在我們的例子中,詐欺為 300 筆、非詐欺為 7,000 筆;若把權重比設為 1:12,就能把樣本的有效比例拉近到詐欺約 1/3、非詐欺約 2/3,這樣就足夠用來訓練模型。

本練習的資料已經切分為訓練集與測試集,所以你只需要專注在定義模型。接著可使用 get_model_results() 這個捷徑函式。它會將模型擬合至你的訓練資料、進行預測,並產生與前面練習步驟類似的效能指標。

本練習屬於課程

Fraud Detection in Python

檢視課程

練習說明

  • 將 weight 選項調整為非詐欺與詐欺比為 1 對 12,並把分割準則設為 'entropy'。
  • 將最大深度設為 10。
  • 將葉節點的最少樣本數設為 10。
  • 將模型中要使用的樹數設為 20。

動手互動練習

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

# Change the model options
model = RandomForestClassifier(bootstrap=True, class_weight={0:____, 1:____}, criterion='____',
			
			# Change depth of model
            max_depth=____,
		
			# Change the number of samples in leaf nodes
            min_samples_leaf=____, 

			# Change the number of trees to use
            n_estimators=____, n_jobs=-1, random_state=5)

# Run the function get_model_results
get_model_results(X_train, y_train, X_test, y_test, model)
編輯並執行程式碼