開始使用免費開始

建立隨機森林模型

你將再次使用 Pima Indians 資料集來預測個體是否患有糖尿病。這次會使用隨機森林分類器。在進行訓練/測試集切分之後,將模型擬合在訓練資料上,並查看特徵重要性。

已為你預先載入特徵與目標資料集 Xy。必要的套件與函式也都已載入完成。

本練習屬於課程

Python 的降維

檢視課程

練習說明

  • 將 test size 設為 25%,也就是進行 75%-25% 的訓練/測試集切分。
  • 將隨機森林分類器擬合到訓練資料。
  • 計算測試集的準確率。
  • 逐一印出各特徵的特徵重要性。

動手互動練習

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

# Perform a 75% training and 25% test data split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=____, random_state=0)

# Fit the random forest model to the training data
rf = RandomForestClassifier(random_state=0)
rf.____(____, ____)

# Calculate the accuracy
acc = accuracy_score(____, ____)

# Print the importances per feature
print(dict(zip(X.columns, rf.____.round(2))))

# Print accuracy
print(f"{acc:.1%} accuracy on test set.") 
編輯並執行程式碼