我正在尝试通过预处理、生成 tf-idf 矩阵,然后应用 K 均值来完成文本文档聚类的经典工作。但是,在经典 20NewsGroup 数据集上测试此工作流程会导致大多数文档聚集到一个集群中。(我最初尝试对 20 个组中的 6 个组中的所有文档进行聚类 - 因此希望聚类成 6 个簇)。
我正在 Apache Spark 中实现此功能,因为我的目的是在数百万个文档上利用此技术。以下是在 Databricks 上用 Pyspark 编写的代码:
#declare path to folder containing 6 of 20 news group categories
path = "/mnt/%s/20news-bydate.tar/20new-bydate-train-lessFolders/*/*" %
MOUNT_NAME
#read all the text files from the 6 folders. Each entity is an entire
document.
text_files = sc.wholeTextFiles(path).cache()
#convert rdd to dataframe
df = text_files.toDF(["filePath", "document"]).cache()
from pyspark.ml.feature import HashingTF, IDF, Tokenizer, CountVectorizer
#tokenize the document text
tokenizer = Tokenizer(inputCol="document", outputCol="tokens") …Run Code Online (Sandbox Code Playgroud)