【问题标题】:Extract top words for each cluster提取每个集群的热门词
【发布时间】:2019-08-13 01:12:39
【问题描述】:

我已经对文本数据进行了 K-means 聚类

#K-means clustering
from sklearn.cluster import KMeans
num_clusters = 4
km = KMeans(n_clusters=num_clusters)
%time km.fit(features)
clusters = km.labels_.tolist()

其中 features 是 tf-idf 向量

#preprocessing text - converting to a tf-idf vector form

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(sublinear_tf=True, min_df=0.01,max_df=0.75, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
features = tfidf.fit_transform(df.keywrds).toarray()
labels = df.CD

然后我将集群标签添加到原始数据集

df['clusters'] = clusters

并按簇索引数据帧

pd.DataFrame(df,index = [clusters])

如何获取每个集群的热门词?

【问题讨论】:

    标签: python-3.x machine-learning k-means tf-idf


    【解决方案1】:

    这并不是每个集群中的排名靠前的单词,而是按最常见的单词排序。然后你可以只将第一个单词作为一个词组而不是一个簇数。

    建立一个包含所有特征名称和 tfidf 分数的字典

    for f, w in zip(tfidf.get_feature_names(), tfidf.idf_):
        featurenames[len(f.split(' '))].append((f, w))
    featurenames = dict(featurenames[1])
    

    四舍五入的特征 idf 值,因为它们有点长

    featurenames = dict(zip(featurenames.keys(), [round(v, 4) for v in featurenames.values()]))
    

    将字典转换为df

    dffeatures = pd.DataFrame.from_dict(featurenames, orient='index').reset_index() \
        .rename(columns={'index': 'featurename',0:'featureid'})
    dffeatures = dffeatures.round(4)
    

    将特征词与 id 结合并创建一个新字典。我这样做是为了适应重复的 ID。

    dffeatures['combined'] = dffeatures.apply(lambda x:'%s:%s' % (x['featureid'],x['featurename']),axis=1)
    featurenamesnew = pd.Series(dffeatures.combined.values, index=dffeatures.featurename).to_dict()
    
    {'cat': '2.3863:cat', 'cow': '3.0794:cow', 'dog': '2.674:dog'....}
    

    在 df 中创建了一个新的 col 并将所有单词替换为 idf:feature value

    df['temp'] = df['inputdata'].replace(featurenamesnew, regex=True)
    

    将 df idf:feature 值升序排列,因此最常见的词首先出现

    df['temp'] = df['temp'].str.split().apply(lambda x: sorted(set(x), reverse=False)).str.join(' ').to_frame()
    

    reverese map idf:featurevalue 与文字

    inv_map = {v: k for k, v in featurenamesnew.items()}
    df['cluster_top_n_words'] = df['temp'].replace(inv_map, regex=True)
    

    最后在新的 df col 中保留前 n 个单词

    df['cluster_top_n_words'] = df['cluster_top_n_words'].apply(lambda x: ' '.join(x.split()[:3]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-13
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2014-02-21
      相关资源
      最近更新 更多