在Scikit-learn中,可以使用TfidfVectorizer和KMeans来实现文本聚类。以下是一个简单的示例代码:
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans # 文本数据 documents = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?', ] # 使用TfidfVectorizer将文本转换成TF-IDF特征 vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(documents) # 使用KMeans进行聚类 kmeans = KMeans(n_clusters=2) kmeans.fit(X) # 输出聚类结果 clusters = kmeans.labels_ for i, text in enumerate(documents): print(f"Document '{text}' belongs to cluster {clusters[i]}")
在上面的代码中,首先使用TfidfVectorizer将文本数据转换成TF-IDF特征,然后使用KMeans进行聚类,最后输出每个文档所属的聚类。可以根据实际情况调整聚类的数量和其他参数来获取更好的聚类效果。