开始使用免费开始使用

K-means on a soccer field(第 2 部分)

在上一个练习中,您已成功使用 k-means 算法对 lineup 数据框中的两支球队进行了聚类。这一次,我们来看看当您将 k 设为 3 时会发生什么。

您会发现算法仍然可以运行,但在这个情境下这样做真的合理吗……

本练习是课程的一部分

R 中的聚类分析

查看课程

练习说明

  • 使用 kmeans() 函数并设置 centers = 3,基于 lineup 数据构建一个名为 model_km3 的 k-means 模型。
  • 从模型中提取聚类分配向量 model_km3$cluster,并将其保存到变量 clust_km3 中。
  • 将聚类分配作为列 cluster 追加到 lineup 数据框中,并将结果保存为新的数据框 lineup_km3
  • 使用 ggplot 绘制每位球员在场上的位置,并按其聚类为点着色。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Build a kmeans model
model_km3 <- ___

# Extract the cluster assignment vector from the kmeans model
clust_km3 <- ___

# Create a new data frame appending the cluster assignment
lineup_km3 <- ___

# Plot the positions of the players and color them using their cluster
ggplot(___, aes(x = ___, y = ___, color = factor(___))) +
  geom_point()
编辑并运行代码