k-means实现文本聚类代码
时间: 2023-09-26 18:09:12 浏览: 51
以下是一个简单的k-means文本聚类的示例代码:
```python
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
# 假设有一些文本数据存储在一个列表中,每个元素代表一篇文章
text_data = ['This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?']
# 使用TfidfVectorizer将文本转换为tf-idf向量
vectorizer = TfidfVectorizer(stop_words='english')
tf_idf = vectorizer.fit_transform(text_data)
# 使用k-means聚类算法将文本数据分成两个簇
kmeans = KMeans(n_clusters=2, random_state=0).fit(tf_idf)
clusters = kmeans.labels_
# 输出每个文本所属的簇
for i in range(len(text_data)):
print("文本“{}”所属的簇为{}".format(text_data[i], clusters[i]))
```
上述代码使用sklearn库中的KMeans类实现了k-means聚类算法。首先,使用TfidfVectorizer将文本转换为tf-idf向量,然后使用KMeans类将向量分成两个簇。最后,输出每个文本所属的簇。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)