训练/测试集划分与计算准确率
现在用 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(____, ____))