【问题标题】:Text clustering using Scipy Hierarchy Clustering in Python在 Python 中使用 Scipy Hierarchy Clustering 进行文本聚类
【发布时间】:2021-04-04 06:02:35
【问题描述】:

我有一个文本语料库,其中包含 1000 多篇文章,每篇文章单独一行。我正在尝试在 python 中使用 Hierarchy Clustering using Scipy 来生成相关文章的集群。 这是我用来做聚类的代码

# Agglomerative Clustering
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as hac
tree = hac.linkage(X.toarray(), method="complete",metric="euclidean")
plt.clf()
hac.dendrogram(tree)
plt.show() 

我得到了这个情节

然后我用 fcluster() 在第三层砍掉树

from scipy.cluster.hierarchy import fcluster
clustering = fcluster(tree,3,'maxclust')
print(clustering)

我得到了这个输出: [2 2 2 ..., 2 2 2]

我的问题是如何找到每个集群中的前 10 个常用词,以便为每个集群建议一个主题?

【问题讨论】:

  • 为什么你认为 3 是一个合适的值?

标签: python scipy cluster-analysis text-mining


【解决方案1】:

您可以执行以下操作:

  1. 将您的结果(您的 clustering 变量)与您的输入(1000 多篇文章)对齐。
  2. 使用 pandas 库,您可以使用 groupby function 并以集群 # 作为其键。
  3. 每组(使用get_group function),为每个组填充一个整数defaultdict 你遇到的词。
  4. 您现在可以按降序对字数字典进行排序,并获得所需的最常用字数。

祝你好运,如果这是你要找的,请接受我的回答。

【讨论】:

    【解决方案2】:

    我愿意。给定一个 df 与文章名称和文章文本类似

    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 6 entries, 0 to 5
    Data columns (total 2 columns):
     #   Column    Non-Null Count  Dtype 
    ---  ------    --------------  ----- 
     0   Argument  6 non-null      object
     1   Article   6 non-null      object
    dtypes: object(2)
    memory usage: 224.0+ bytes
    

    创建文章矩阵

    from scipy.cluster.hierarchy import linkage, fcluster
    from sklearn.feature_extraction.text import CountVectorizer
    
    # initialize
    cv = CountVectorizer(stop_words='english') 
    cv_matrix = cv.fit_transform(df['Article']) 
    # create document term matrix
    df_dtm = pd.DataFrame(
        cv_matrix.toarray(), 
        index=df['Argument'].values, 
        columns=cv.get_feature_names()
    )
    tree = hierarchy.linkage(df_dtm, method="complete", metric="euclidean")
    

    然后得到选择的聚类

    clustering = fcluster(tree, 2, 'maxclust')
    

    并将集群添加到df_dtm

    df_dtm['_cluster_'] = clustering
    df_dtm.index.name = '_article_'
    df_word_count = df_dtm.groupby('_cluster_').sum().reset_index().melt(
        id_vars=['_cluster_'], var_name='_word_', value_name='_count_'
    )
    

    最后取第一个最常用的词

    words_1 = df_word_count[df_word_count._cluster_==1].sort_values(
        by=['_count_'], ascending=False).head(3)
    words_2 = df_word_count[df_word_count._cluster_==2].sort_values(
        by=['_count_'], ascending=False).head(3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 2021-06-27
      • 2017-11-23
      • 2013-09-15
      • 1970-01-01
      • 2015-05-13
      • 2019-01-06
      • 2015-03-09
      相关资源
      最近更新 更多