doc2vec 如何聚类 DocvecsArray

我从网上找到的例子中拼凑了以下代码:

# gensim modulesfrom gensim import utilsfrom gensim.models.doc2vec import LabeledSentencefrom gensim.models import Doc2Vecfrom sklearn.cluster import KMeans# randomfrom random import shuffle# classifierclass LabeledLineSentence(object):    def __init__(self, sources):        self.sources = sources        flipped = {}        # make sure that keys are unique        for key, value in sources.items():            if value not in flipped:                flipped[value] = [key]            else:                raise Exception('Non-unique prefix encountered')    def __iter__(self):        for source, prefix in self.sources.items():            with utils.smart_open(source) as fin:                for item_no, line in enumerate(fin):                    yield LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no])    def to_array(self):        self.sentences = []        for source, prefix in self.sources.items():            with utils.smart_open(source) as fin:                for item_no, line in enumerate(fin):                    self.sentences.append(LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))        return self.sentences    def sentences_perm(self):        shuffle(self.sentences)        return self.sentencessources = {'test.txt' : 'DOCS'}sentences = LabeledLineSentence(sources)model = Doc2Vec(min_count=1, window=10, size=100, sample=1e-4, negative=5, workers=8)model.build_vocab(sentences.to_array())for epoch in range(10):    model.train(sentences.sentences_perm())print(model.docvecs)

我的 test.txt 文件每行包含一段文字。

代码运行正常并为每行文本生成 DocvecsArray

我的目标是得到如下输出:

cluster 1: [DOC_5,DOC_100,…DOC_N]
cluster 2: [DOC_0,DOC_1,…DOC_N]

我找到了以下回答,但输出是:

cluster 1: [word,word…word]
cluster 2: [word,word…word]

如何修改代码以获取文档聚类?


回答:

看起来你已经接近目标了。

你输出一组向量。对于 sklearn 包,你需要将这些向量放入 numpy 数组中 – 使用 numpy.toarray() 函数可能是最佳选择。KMeans 的文档非常出色,整个库的文档也很好。

我给你一个建议,我使用 DBSCAN 的效果比 KMeans 好得多,这两个都在同一个 sklearn 库中。DBSCAN 不需要你指定输出中想要的聚类数量。

这两个链接中都有详细注释的代码示例。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注