訓練/測試切分與計算準確率
現在用 churn_df 資料集來練習把資料切成訓練集與測試集吧!
已為你建立 NumPy 陣列,特徵為 X,目標變數為 y。
本練習屬於課程
使用 scikit-learn 進行監督式學習
練習說明
- 從
sklearn.model_selection匯入train_test_split。 - 將
X與y切分為訓練集與測試集,將test_size設為 20%,random_state設為42,並確保目標標籤比例與原始資料集相同。 - 將
knn模型擬合到訓練資料。 - 計算並印出該模型在測試資料上的準確率。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the module
from ____ import ____
X = churn_df.drop("churn", axis=1).values
y = churn_df["churn"].values
# Split into training and test sets
X_train, X_test, y_train, y_test = ____(____, ____, test_size=____, random_state=____, stratify=____)
knn = KNeighborsClassifier(n_neighbors=5)
# Fit the classifier to the training data
____
# Print the accuracy
print(knn.score(____, ____))