我使用MySentences类从目录中的所有文件中提取句子,并使用这个句子来训练word2vec模型。我的数据集没有标签。
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname):
for line in open(os.path.join(self.dirname, fname)):
yield line.split()
sentences = MySentences('sentences')
model = gensim.models.Word2Vec(sentences)现在,我想使用这个类来创建一个doc2vec模型。我读了Doc2Vec参考页。Doc2Vec()函数将句子作为参数,但它不接受上述语句变量并返回错误:
AttributeError: 'list' object has no attribute 'words'有什么问题吗?正确的参数类型是什么?
更新:
我想,没有标签的数据才是问题所在。doc2vec似乎需要标记数据。
发布于 2016-07-07 16:20:06
没有理由使用额外的类来解决这个问题。在新的库更新中,添加了一个新的函数TaggedLineDocument,将语句转换为向量。
sentences = TaggedLineDocument(INPUT_FILE)然后,训练模型
model = Doc2Vec(alpha=0.025, min_alpha=0.025)
model.build_vocab(sentences)
for epoch in range(10):
model.train(sentences)
model.alpha -= 0.002
model.min_alpha = model.alpha
print epoch发布于 2018-10-16 18:48:56
与word2vec不同,doc2vec需要用唯一的id标记每个列车入口。这是必要的,因为稍后当它预测相似之处时,其结果将是doc (火车条目的唯一it ),就像单词是对word2vec的预测一样。
下面是我的一段代码,它完成了您想要实现的目标。
class DynamicCorpus(object):
def __iter__(self):
with open(csf_file) as fp:
for line in fp:
splt = line.split(':')
text = splt[2].replace('\n', '')
id = splt[0]
yield TaggedDocument(text.split(), [id])我的csv文件有id:text格式。
稍后,您只需将语料库提供给模型。
coprus = DynamicCorpus()
d2v = doc2vec.Doc2Vec(min_count=15,
window=10,
vector_size=300,
workers=15,
alpha=0.025,
min_alpha=0.00025,
dm=1)
d2v.build_vocab(corpus)
for epoch in range(training_iterations):
d2v.train(corpus, total_examples=d2v.corpus_count, epochs=d2v.iter)
d2v.alpha -= 0.0002
d2v.min_alpha = d2v.alphahttps://stackoverflow.com/questions/38245739
复制相似问题