开始使用免费开始使用

训练/测试集划分与计算准确率

现在用 churn_df 数据集练习将数据划分为训练集和测试集吧!

我们已为您创建了 NumPy 数组:特征为 X,目标变量为 y

本练习是课程的一部分

使用 scikit-learn 的监督学习

查看课程

练习说明

  • sklearn.model_selection 导入 train_test_split
  • Xy 划分为训练集与测试集,设置 test_size 为 20%,random_state42,并确保目标标签的比例与原始数据集一致。
  • 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(____, ____))
编辑并运行代码