【问题标题】:Scikit Learn K-means Clustering & TfidfVectorizer: How to pass top n terms with highest tf-idf score to k-meansScikit Learn K-means Clustering & TfidfVectorizer:如何将具有最高 tf-idf 分数的前 n 项传递给 k-means
【发布时间】:2020-01-11 08:14:12
【问题描述】:

我正在基于 TFIDF 矢量化器对文本数据进行聚类。代码工作正常。它将整个 TFIDF 矢量化器输出作为 K-Means 聚类的输入并生成散点图。相反,我只想发送基于 TF-IDF 分数的前 n 项作为 k-means 聚类的输入。有没有办法做到这一点?

vect = TfidfVectorizer(ngram_range=(1,3),stop_words='english')

tfidf_matrix = vect.fit_transform(df_doc_wholetext['csv_text'])


'''create k-means model with custom config '''
clustering_model = KMeans(
    n_clusters=num_clusters,
    max_iter=max_iterations,
    precompute_distances="auto",
    n_jobs=-1
)

labels = clustering_model.fit_predict(tfidf_matrix)

x = tfidf_matrix.todense()

reduced_data = PCA(n_components=pca_num_components).fit_transform(x)


fig, ax = plt.subplots()
for index, instance in enumerate(reduced_data):        
    pca_comp_1, pca_comp_2 = reduced_data[index]
    color = labels_color_map[labels[index]]
    ax.scatter(pca_comp_1,pca_comp_2, c = color)
plt.show()

【问题讨论】:

    标签: python scikit-learn k-means text-mining tfidfvectorizer


    【解决方案1】:

    使用 TfidfVectorizer 中的 max_features 来考虑前 n 个特征

    vect = TfidfVectorizer(ngram_range=(1,3),stop_words='english', max_features=n)
    

    根据 scikit-learn 的文档,max_features 采用 int 或 None 的值(默认=None)。如果不是 None,TfidfVectorizer 会构建一个词汇表,该词汇表仅考虑按词频在整个语料库中排序的最高 max_features。

    这里是link

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 1970-01-01
      • 2013-07-03
      • 2018-01-25
      • 2013-10-12
      • 2012-07-02
      • 2021-01-19
      • 2020-09-08
      • 2018-01-29
      相关资源
      最近更新 更多