我有两个目录,我想从中读取它们的文本文件并给它们贴上标签,但我不知道如何通过taggedDocument来实现这一点。我以为它可以作为标记文档([strings],[labels])工作,但这显然不起作用。

from gensim import models
from gensim.models.doc2vec import TaggedDocument
import utilities as util
import os
from sklearn import svm
from nltk.tokenize import sent_tokenize
CogPath = "./FixedCog/"
NotCogPath = "./FixedNotCog/"
SamplePath ="./Sample/"
docs = []
tags = []
CogList = [p for p in os.listdir(CogPath) if p.endswith('.txt')]
NotCogList = [p for p in os.listdir(NotCogPath) if p.endswith('.txt')]
SampleList = [p for p in os.listdir(SamplePath) if p.endswith('.txt')]
for doc in CogList:
str = open(CogPath+doc,'r').read().decode("utf-8")
docs.append(str)
print docs
tags.append(doc)
print "###########"
print tags
print "!!!!!!!!!!!"
for doc in NotCogList:
str = open(NotCogPath+doc,'r').read().decode("utf-8")
docs.append(str)
tags.append(doc)
for doc in SampleList:
str = open(SamplePath + doc, 'r').read().decode("utf-8")
docs.append(str)
tags.append(doc) T = TaggedDocument(docs,tags) model = models.Doc2Vec(T,alpha=.025, min_alpha=.025, min_count=1,size=50)

错误

Traceback (most recent call last):
File "/home/farhood/PycharmProjects/word2vec_prj/doc2vec.py", line 34, in <module>
model = models.Doc2Vec(T,alpha=.025, min_alpha=.025, min_count=1,size=50)
File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/doc2vec.py", line 635, in __init__
self.build_vocab(documents, trim_rule=trim_rule)
File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/word2vec.py", line 544, in build_vocab
self.scan_vocab(sentences, progress_per=progress_per, trim_rule=trim_rule) # initial survey
File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/doc2vec.py", line 674, in scan_vocab
if isinstance(document.words, string_types):
AttributeError: 'list' object has no attribute 'words'

所以我只是做了一些测试,在Github上发现了这一点:

class TaggedDocument(namedtuple('TaggedDocument', 'words tags')):
"""
A single document, made up of `words` (a list of unicode string tokens)
and `tags` (a list of tokens). Tags may be one or more unicode string
tokens, but typical practice (which will also be most memory-efficient) is
for the tags list to include a unique integer id as the only tag. Replaces "sentence as a list of words" from Word2Vec.

因此,我决定通过为每个文档生成一个taggedDocument类来更改使用taggedDocument函数的方式,重要的是必须将标记作为列表传递。

for doc in CogList:
str = open(CogPath+doc,'r').read().decode("utf-8")
str_list = str.split()
T = TaggedDocument(str_list,[doc])
docs.append(T)

doc2vec模型的输入应该是taggeddocument的列表(['list'、'of'、'word']、[tag_])。一个好的实践是使用句子的索引作为标记。例如,用两个句子(即文档、段落)训练doc2vec模型:

s1 = 'the quick fox brown fox jumps over the lazy dog'
s1_tag = ''
s2 = 'i want to burn a zero-day'
s2_tag = '' docs = []
docs.append(TaggedDocument(words=s1.split(), tags=[s1_tag])
docs.append(TaggedDocument(words=s2.split(), tags=[s2_tag]) model = gensim.models.Doc2Vec(vector_size=300, window=5, min_count=5, workers=4, epochs=20)
model.build_vocab(docs) print 'Start training process...'
model.train(docs, total_examples=model.corpus_count, epochs=model.iter) #save model
model.save(model_path)

您可以使用Gensim的常用文本作为示例:

from gensim.test.utils import common_texts
from gensim.models.doc2vec import Doc2Vec, TaggedDocument documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(common_texts)]
model = Doc2Vec(documents, vector_size=5, window=2, min_count=1, workers=4)

gensim中TaggedDocument 怎么使用的更多相关文章

  1. gensim中word2vec

    from gensim.models import Word2Vec Word2Vec(self, sentences=None, size=100, alpha=0.025, window=5, m ...

  2. 全网独发gensim中similarities.Similarity用法

    index = similarities.MatrixSimilarity(lsi[corpus]) # 管网的原文翻译如下: 警告:similarities.MatrixSimilarity类仅仅适 ...

  3. gensim中word2vec和其他一些向量的使用

    直接上代码吧,word2vec # test from gensim.models.word2vec import Word2Vec txt_file = open('data.txt') sente ...

  4. doc2vec使用说明(二)gensim工具包 LabeledSentence

    欢迎交流,转载请注明出处. 本文介绍gensim工具包中,带标签(一个或者多个)的文档的doc2vec 的向量表示. 应用场景: 当每个文档不仅可以由文本信息表示,还有别的其他标签信息时,比如,在商品 ...

  5. Gensim进阶教程:训练word2vec与doc2vec模型

    本篇博客是Gensim的进阶教程,主要介绍用于词向量建模的word2vec模型和用于长文本向量建模的doc2vec模型在Gensim中的实现. Word2vec Word2vec并不是一个模型--它其 ...

  6. 用gensim学习word2vec

    在word2vec原理篇中,我们对word2vec的两种模型CBOW和Skip-Gram,以及两种解法Hierarchical Softmax和Negative Sampling做了总结.这里我们就从 ...

  7. 文本分布式表示(三):用gensim训练word2vec词向量

    今天参考网上的博客,用gensim训练了word2vec词向量.训练的语料是著名科幻小说<三体>,这部小说我一直没有看,所以这次拿来折腾一下. <三体>这本小说里有不少人名和一 ...

  8. 解决在使用gensim.models.word2vec.LineSentence加载语料库时报错 UnicodeDecodeError: 'utf-8' codec can't decode byte......的问题

    在window下使用gemsim.models.word2vec.LineSentence加载中文维基百科语料库(已分词)时报如下错误: UnicodeDecodeError: 'utf-8' cod ...

  9. python 全栈开发,Day133(玩具与玩具之间的对话,基于jieba gensim pypinyin实现的自然语言处理,打包apk)

    先下载github代码,下面的操作,都是基于这个版本来的! https://github.com/987334176/Intelligent_toy/archive/v1.6.zip 注意:由于涉及到 ...

随机推荐

  1. GPIO软件模拟IIC时序

    一.MPU6050中的IIC时序 1.1 START和STOP SDA和SCL在高电平时,SDA拉低表示START.SCL拉低,表示可以传输数据. SDA和SCL在低电平时,SDA拉高表示STOP. ...

  2. error LNK2001: 无法解析的外部符号 __imp__Shell_NotifyIconA@8

    编译链接报错 error LNK2001: 无法解析的外部符号 __imp__Shell_NotifyIconA@8 解决方案: 在代码中添加链接库Shell32.lib #pragma commen ...

  3. java并发编程笔记(五)——线程安全策略

    java并发编程笔记(五)--线程安全策略 不可变得对象 不可变对象需要满足的条件 对象创建以后其状态就不能修改 对象所有的域都是final类型 对象是正确创建的(在对象创建期间,this引用没有逸出 ...

  4. centos 7 下升级自带 sqlite3

    问题 在 centos 7 上面运行 django 2.2 开发服务器时出现: django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or ...

  5. 用processing生成屏保程序

    想法 利用随机数控制圆圈的大小.位置以及颜色,可以产生随机的美感. 让小球动起来,并且在屏幕边界处产生反弹效果. 代码 1: float circle_x = (float) 0.0; 2: floa ...

  6. 单机zookeeper部署伪集群

    1.zookeeper介绍 ZooKeeper 是一个为分布式应用所设计的分布的.开源的协调服务.分布式的应用可以建立在同步.配置管理.分组和命名等服务的更高级别的实现的基础之上. ZooKeeper ...

  7. leetcode.双指针.633平方数之和-Java

    1. 具体题目 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c. 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 注 ...

  8. 使用pip安装python模块和包

    点击进入幕布视图浏览 https://mubu.com/doc/a8VGCUfqqw 五.使用pip安装python第三方库. pip的常用命令 方式一:在线安装 1.进入命令行 2.敲入pip命令: ...

  9. [轉]User namespaces – available to play!

    User namespaces – available to play! Posted on May 10, 2012by s3hh Over the past few months, Eric Bi ...

  10. 防止按钮重复点击的思路(js篇)

    最直接的思路可能就是点击按钮后,按钮的事件绑定函数解绑,1s后重新绑定函数 <button id=</button> <script> btn.onclick = fun ...