我的代码里怎么看聚类结果?df = pd.read_csv('/Users/dashan/postgraduate/研一下/4_LIU_positive_compute/期末/期末作业-文本分析/期末作业-操作.csv', encoding='gbk') # 设置停用词 stopwords = set() content = [line.strip() for line in open('/Users/dashan/postgraduate/研一下/4_LIU_positive_compute/期末/期末作业-文本分析/hit_stopwords.txt','r',encoding='utf-8').readlines()] # print(content) stopwords.update(content) jieba.load_userdict(stopwords) # 对文本数据进行分词 df['content_cut'] = df['微博正文'].apply(lambda x: ' '.join(jieba.cut(x))) # print(df['content_cut']) # 构建TF-IDF矩阵 tfidf = TfidfVectorizer() tfidf_matrix = tfidf.fit_transform(df['content_cut']) print(tfidf_matrix) # 聚类分析 n_cluster = 3 kmeans = KMeans(n_clusters=n_cluster, random_state=0) kmeans.fit(tfidf_matrix) # 将聚类结果添加到原始数据中 df['cluster'] = kmeans.labels_ # 生成词云图 for i in range(n_cluster): text = ' '.join(df[df['cluster']==i]['content_cut']) wordcloud = WordCloud( stopwords=stopwords, background_color='white', width=800, height=600,font_path='/System/Library/Fonts/Supplemental/Songti.ttc').generate(text) plt.imshow(wordcloud) plt.axis('off') plt.show()
时间: 2024-03-14 19:47:14 浏览: 24
在你的代码中,聚类结果已经被存储在了 `df['cluster']` 列中,每个样本被分配到了一个聚类簇。你可以使用 Pandas 的一些函数来查看聚类结果,例如:
1. 查看每个聚类簇的样本数:
```python
print(df['cluster'].value_counts())
```
2. 查看每个聚类簇的样本:
```python
for i in range(n_cluster):
print(f'Cluster {i}:')
print(df[df['cluster']==i]['微博正文'])
```
你也可以通过可视化来更好地查看聚类结果。例如,你可以使用 Seaborn 的 `scatterplot` 函数绘制每个样本的分布情况,并使用不同的颜色表示不同的聚类簇:
```python
import seaborn as sns
sns.scatterplot(x='x_axis', y='y_axis', hue='cluster', data=df)
```
其中,`x_axis` 和 `y_axis` 分别是你使用 PCA 或 t-SNE 降维后得到的两个维度,`hue` 参数指定了颜色映射的变量,即聚类簇。
相关问题
聚类分析的结果怎么看?import pandas as pd import jieba from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from wordcloud import WordCloud import matplotlib.pyplot as plt # 读取中文文本数据 df = pd.read_csv('/Users/dashan/postgraduate/研一下/4_LIU_positive_compute/期末/期末作业-文本分析/期末作业-操作.csv', encoding='gbk') # 设置停用词 stopwords = set() content = [line.strip() for line in open('/Users/dashan/postgraduate/研一下/4_LIU_positive_compute/期末/期末作业-文本分析/hit_stopwords.txt','r',encoding='utf-8').readlines()] # print(content) stopwords.update(content) jieba.load_userdict(stopwords) # 对文本数据进行分词 df['content_cut'] = df['微博正文'].apply(lambda x: ' '.join(jieba.cut(x))) # print(df['content_cut']) # 构建TF-IDF矩阵 tfidf = TfidfVectorizer() tfidf_matrix = tfidf.fit_transform(df['content_cut']) print(tfidf_matrix) # 聚类分析 n_cluster = 3 kmeans = KMeans(n_clusters=n_cluster, random_state=0) kmeans.fit(tfidf_matrix) # 将聚类结果添加到原始数据中 df['cluster'] = kmeans.labels_
在这段代码中,通过对中文文本数据进行分词和构建 TF-IDF 矩阵,然后使用 KMeans 聚类算法将文本数据分为 n_cluster 个簇。每个簇代表一个主题或者一个类别,可以通过观察每个簇中的文本数据的内容来理解这个簇所代表的主题或类别。
在这里,我们可以通过查看每个簇中的文本数据来了解聚类结果。可以使用 Pandas 的 groupby 函数将原始数据按照 cluster 列进行分组,然后查看每个簇中的微博正文内容:
```
groups = df.groupby('cluster')
for i in range(n_cluster):
print('Cluster %d:' % i)
print(groups.get_group(i)['微博正文'].tolist())
print()
```
此外,我们还可以使用词云图来可视化聚类结果。可以将每个簇中的微博正文内容合并为一个字符串,然后使用 WordCloud 库生成词云图。以下是示例代码:
```
for i in range(n_cluster):
text = ' '.join(groups.get_group(i)['微博正文'].tolist())
wordcloud = WordCloud(background_color='white', width=800, height=600).generate(text)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
```
这样可以生成 n_cluster 张词云图,每张词云图代表一个簇。通过观察词云图中出现频率较高的词语,可以初步了解该簇所代表的主题或类别。
data = pd.read_excel("D:/PycharmProjects/cluster220422/聚类后数据1000_excel/" + cond) # # print(data) # # 首先将pandas读取的数据转化为array # data = np.array(data) # # 然后转化为list形式 # data = data.tolist() # # print(data),df = pd.read_csv("F:/XH_WY_ZH_ALL/XH_WY_ZH_ALL/XH_WY_ZH_ALL/" + cond) # os.mkdir(r"G:/功图/" + cond) # 选择需要提取的两列数据 col1 = df['WY'] col2 = df['ZH'] # 合并两列数据 new_col = col1.astype(str) + ',' + col2.astype(str) # 将合并后的数据保存为新文件 new_df = pd.DataFrame({'WYZH': new_col}) # 分列 new_df = new_df['WYZH'].str.split(',', expand=True) new_df = pd.DataFrame(new_df) # 首先将pandas读取的数据转化为array data = np.array(new_df) # 然后转化为list形式 data = data.tolist() # print(data)如何让第二个代码输出的数据和第一代码的输出格式相同
可以使用 pandas 中的 to_numpy() 方法将 DataFrame 对象转换为 numpy 数组,然后再使用 numpy 数组的 tolist() 方法将其转换为列表,最终得到和第一段代码输出格式相同的数据。修改后的代码如下:
```
import pandas as pd
import numpy as np
df = pd.read_csv("F:/XH_WY_ZH_ALL/XH_WY_ZH_ALL/XH_WY_ZH_ALL/" + cond)
col1 = df['WY']
col2 = df['ZH']
new_col = col1.astype(str) + ',' + col2.astype(str)
new_df = pd.DataFrame({'WYZH': new_col})
new_df[['WY', 'ZH']] = new_df['WYZH'].str.split(',', expand=True)
data = new_df[['WY', 'ZH']].to_numpy().tolist()
print(data)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)