我很想知道为什么这个程序只创造了一个充满生机的字母,而不是文字。我是否为word2vec提供了错误的数据?如果我使用
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
['this', 'is', 'the', 'second', 'sentence'],
['yet', 'another', 'sentence'],
['one', 'more', 'sentence'],
['and', 'the', 'final', 'sentence']]
# train model
model = Word2Vec(sentences, min_count=1)这代替了我的数据的文本文档。
import string
from keras.preprocessing.text import Tokenizer
from sklearn.feature_extraction.text import TfidfVectorizer
from gensim.models import Word2Vec
from sklearn.decomposition import PCA
from matplotlib import pyplot
filename = 'book.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
words1 = list(text.split())
words1 = [word.lower() for word in words1]
table = str.maketrans('', '', string.punctuation)
removepunct = [w.translate(table) for w in words1]
print(removepunct[:100])
# train model
model = Word2Vec(removepunct, min_count=1)
# fit a 2D PCA model to the vectors
X = model.wv[model.wv.key_to_index]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
# create a scatter plot of the projection
pyplot.scatter(result[:, 0], result[:, 1])
words = list(model.wv.key_to_index)
for i, word in enumerate(words):
pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
pyplot.show()发布于 2022-05-06 19:30:13
我认为这里的问题是,removepunct不是一个标记列表。如果removepunct是一个令牌列表,那么gensim的Word2Vec模型将将令牌中的每个字符视为令牌。
发布于 2022-05-06 19:33:50
你的成功例子是一个句子列表,也就是一个单词列表。第二次,您传递给它一个字符串列表,Python按照它通常的Python方式,一次迭代字符串一个字母,而不是迭代单词列表。
nltk提供了将文本文件摘要为句子列表的高级方法。以下是一种获得标记化句子的简单方法:
from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader(".", ["book.txt"])
model = Word2Vec(corpus.sents(), min_count=1)
# Continue as before如果要删除标点符号,必须在输入被解析为句子(因为标点符号很重要)之后进行,如下所示:
clean_sents = [ [w for w in s if w.isalnum()] for s in corpus.sents() ]https://stackoverflow.com/questions/72146448
复制相似问题