【问题标题】:Training Doc2Vec on 20newsgroups dataset. Getting Exception AttributeError: 'str' object has no attribute 'words'在 20newsgroups 数据集上训练 Doc2Vec。获取异常AttributeError:'str'对象没有属性'words'
【发布时间】:2017-04-13 23:58:19
【问题描述】:

Gensim Doc2Vec Exception AttributeError: 'str' object has no attribute 'words' 这里有一个类似的问题,但没有得到任何有用的答案。

我正在尝试在 20newsgroups 语料库上训练 Doc2Vec。 以下是我构建词汇的方法:

from sklearn.datasets import fetch_20newsgroups
    def get_data(subset):
        newsgroups_data = fetch_20newsgroups(subset=subset, remove=('headers', 'footers', 'quotes'))
        docs = []
        for news_no, news in enumerate(newsgroups_data.data):       
            tokens = gensim.utils.to_unicode(news).split() 
            if len(tokens) == 0:
                continue
            sentiment =  newsgroups_data.target[news_no]
            tags = ['SENT_'+ str(news_no), str(sentiment)]
            docs.append(TaggedDocument(tokens, tags))
        return docs

    train_docs = get_data('train')
    test_docs = get_data('test')
    alldocs = train_docs + test_docs

    model = Doc2Vec(dm=dm, size=size, window=window, alpha = alpha, negative=negative, sample=sample, min_count = min_count, workers=cores, iter=passes)
    model.build_vocab(alldocs)

然后我训练模型并保存结果:

model.train(train_docs, total_examples = len(train_docs), epochs = model.iter)
model.train_words = False
model.train_labels = True
model.train(test_docs, total_examples = len(test_docs), epochs = model.iter)

model.save(output)

当我尝试加载模型时出现问题: screen

我试过了:

  • 使用 LabeledSentence 代替 TaggedDocument

  • 产生 TaggedDocument 而不是将它们附加到列表中

  • 将 min_count 设置为 1,这样就不会忽略任何单词(以防万一)

python2 和 python3 也出现问题。

请帮我解决这个问题。

【问题讨论】:

    标签: python-2.7 python-3.x doc2vec


    【解决方案1】:

    您已在非现场 (imgur) 'screen' 链接中隐藏了最重要的信息——触发错误的确切代码以及错误文本本身。 (这将是剪切和粘贴到问题中的理想文本,而不是其他似乎运行正常但不会触发错误的步骤。)

    看那张截图,有一行:

    model = Doc2Vec("20ng_infer")
    

    ...触发错误。

    请注意,documented for the Doc2Vec() initialization method 中的所有参数都不是纯字符串,就像上一行中的 "20ng_infer" 参数一样——所以这不太可能做任何有用的事情。

    如果尝试加载以前使用model.save() 保存的模型,您应该使用Doc2Vec.load()——它将采用描述本地文件路径的字符串来加载模型。所以试试:

    model = Doc2Vec.load("20ng_infer")
    

    (另请注意,较大的模型可能会保存到多个文件中,所有文件都以您提供给save() 的字符串开头,并且这些文件必须一起保存/移动,以便将来再次重新load() 它们。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      相关资源
      最近更新 更多