7du*_*uck 1 python nlp gensim word2vec
看完这篇文章后,我开始训练自己的模型.问题是,作者没有说清楚的东西sentences中 Word2Vec应该是这样的.
我从维基百科页面下载文本,因为它写的是文章,我从中列出了句子:
sentences = [word for word in wikipage.content.split('.')]
Run Code Online (Sandbox Code Playgroud)
所以,例如,sentences[0]看起来像:
'Machine learning is the subfield of computer science that gives computers the ability to learn without being explicitly programmed'
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用此列表训练模型:
model = Word2Vec(sentences, min_count=2, size=50, window=10, workers=4)
Run Code Online (Sandbox Code Playgroud)
但该模型的字典由字母组成!例如,输出model.wv.vocab.keys()是:
dict_keys([',', 'q', 'D', 'B', 'p', 't', 'o', '(', ')', '0', 'V', ':', 'j', 's', 'R', '{', 'g', '-', 'y', 'c', '9', 'I', '}', '1', 'M', ';', '`', '\n', 'i', 'r', 'a', 'm', '–', 'v', 'N', 'h', '/', 'P', 'F', '8', '"', '’', 'W', 'T', 'u', 'U', '?', ' ', 'n', '2', '=', 'w', 'C', 'O', '6', '&', 'd', '4', 'S', 'J', 'E', 'b', 'L', '$', 'l', 'e', 'H', '?', 'f', 'A', "'", 'x', '\\', 'K', 'G', '3', '%', 'k', 'z'])
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?提前致谢!
Word2Vec模型对象的输入可以是单词列表的列表,使用以下标记化函数nltk:
>>> import wikipedia
>>> from nltk import sent_tokenize, word_tokenize
>>> page = wikipedia.page('machine learning')
>>> sentences = [word_tokenize(sent) for sent in sent_tokenize(page.content)]
>>> sentences[0]
['Machine', 'learning', 'is', 'the', 'subfield', 'of', 'computer', 'science', 'that', 'gives', 'computers', 'the', 'ability', 'to', 'learn', 'without', 'being', 'explicitly', 'programmed', '.']
Run Code Online (Sandbox Code Playgroud)
喂它:
>>> from gensim.models import Word2Vec
>>> model = Word2Vec(sentences, min_count=2, size=50, window=10,
>>> list(model.wv.vocab.keys())[:10]
['sparsely', '(', 'methods', 'their', 'typically', 'information', 'assessment', 'False', 'often', 'problems']
Run Code Online (Sandbox Code Playgroud)
但一般来说,包含生成器(单词)的生成器(句子)也可以工作,即:
>>> from gensim.utils import tokenize
>>> paragraphs = map(tokenize, page.content.split('\n')) # paragraphs
>>> model = Word2Vec(paragraphs, min_count=2, size=50, window=10, workers=4)
>>> list(model.wv.vocab.keys())[:10]
['sparsely', 'methods', 'their', 'typically', 'information', 'assessment', 'False', 'often', 'problems', 'symptoms']
Run Code Online (Sandbox Code Playgroud)