TF-IDF文本聚类并显示前五个的python代码
时间: 2024-04-14 21:29:05 浏览: 16
请使用以下Python代码进行TF-IDF文本聚类,并显示前五个聚类结果:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
# 假设有一个包含文本的列表,名为documents
documents = [
"This is the first document",
"This document is the second document",
"And this is the third one",
"Is this the first document"
]
# 使用TF-IDF向量化文本
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)
# 使用KMeans进行聚类
k = 5 # 聚类数目
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)
# 获取每个文本所属的聚类标签
labels = kmeans.labels_
# 打印每个聚类的前五个文本
for i in range(k):
cluster_docs = [documents[j] for j in range(len(documents)) if labels[j] == i]
print(f"Cluster {i+1}:")
for doc in cluster_docs[:5]:
print("- ", doc)
print()
```
这段代码使用了`TfidfVectorizer`将文本转换为TF-IDF特征向量,然后使用`KMeans`进行聚类。最后,我们打印出每个聚类的前五个文本。请注意,这只是一个简单的示例,实际应用中可能需要更多的数据预处理和调参。