开始使用免费开始使用

电影簇中的高频术语

现在您已经创建了稀疏矩阵,请生成簇中心,并打印每个簇中排名前三的术语。使用 .todense() 方法将稀疏矩阵 tfidf_matrix 转换为普通矩阵,以便 kmeans() 函数处理。然后,使用 .get_feature_names() 方法从 tfidf_vectorizer 对象中获取术语列表。Python 中的 zip() 函数可以将两个列表配对。

本练习已保留上一题中的 tfidf_vectorizer 对象和稀疏矩阵 tfidf_matrix。来自 SciPy 的 kmeans 已导入。

当数据点数量更大时,形成的簇会更清晰。不过这需要一定的计算能力,在此类练习环境中较难完全实现。

本练习是课程的一部分

Python 中的聚类分析

查看课程

练习说明

  • 通过 kmeans() 函数生成簇中心。
  • tfidf_vectorizer 对象生成术语列表。
  • 打印每个簇的前 3 个术语。

交互式实操练习

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

num_clusters = 2

# Generate cluster centers through the kmeans function
cluster_centers, distortion = ____

# Generate terms from the tfidf_vectorizer object
terms = tfidf_vectorizer.____()

for i in range(num_clusters):
    # Sort the terms and print top 3 terms
    center_terms = dict(zip(____, ____))
    sorted_terms = sorted(____, key=center_terms.get, reverse=True)
    print(____)
编辑并运行代码