【问题标题】:Document clustering using Mean Shift使用 Mean Shift 进行文档聚类
【发布时间】:2018-02-21 08:26:24
【问题描述】:

我拿了一堆文档并为所有文档中的每个标记计算 tf*idf 并为每个文档创建向量(每个 n 维,n 是语料库中唯一单词的数量)。我无法弄清楚如何使用 sklearn.cluster.MeanShift 从向量创建集群

【问题讨论】:

  • 计算tfidf后,是否有数值矩阵(即:行列数据表)?它是稀疏的还是密集的?一般是什么类型的?您是否使用了 sklearn 中的 TfidfVectorizer()?
  • 是的,我使用 TfidfVectorizer() 得到了一个稀疏矩阵。我不明白如何将其作为 sklearn.clister.MeanShift 的输入

标签: python-3.x scikit-learn cluster-analysis mean-shift


【解决方案1】:

TfidfVectorizer 将文档转换为数字的“稀疏矩阵”。 MeanShift 要求传递给它的数据是“密集的”。下面,我将展示如何在管道中转换它 (credit),但是,如果内存允许,您可以使用 toarray()todense() 将稀疏矩阵转换为密集矩阵。

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import MeanShift
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer

documents = ['this is document one',
             'this is document two',
             'document one is fun',
             'document two is mean',
             'document is really short',
             'how fun is document one?',
             'mean shift... what is that']

pipeline = Pipeline(
  steps=[
    ('tfidf', TfidfVectorizer()),
    ('trans', FunctionTransformer(lambda x: x.todense(), accept_sparse=True)),
    ('clust', MeanShift())
  ])

pipeline.fit(documents)
pipeline.named_steps['clust'].labels_

result = [(label,doc) for doc,label in zip(documents, pipeline.named_steps['clust'].labels_)]

for label,doc in sorted(result):
  print(label, doc)

打印:

0 document two is mean
0 this is document one
0 this is document two
1 document one is fun
1 how fun is document one?
2 mean shift... what is that
3 document is really short

您可以修改“超参数”,但我认为这会给您一个大致的概念。

【讨论】:

  • 如果输入是一个csv,每一行都是关键字或句子。我尝试添加以下内容
  • import csv with open('4.csv', 'r', encoding='utf-8') as f: reader = csv.reader(f) your_list = list(reader) print( your_list)
猜你喜欢
  • 2014-05-10
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
  • 2013-06-08
  • 2015-05-13
  • 2020-08-29
  • 2018-06-24
  • 2014-10-02
相关资源
最近更新 更多