【发布时间】:2018-08-30 07:46:24
【问题描述】:
我有第一本 txt 格式的哈利波特书。由此,我创建了两个新的 txt 文件:第一个,所有出现的 Hermione 都被替换为 Hermione_1;第二,Hermione 的所有出现都被替换为Hermione_2。然后我将这两个文本连接起来创建一个长文本,并将其用作 Word2Vec 的输入。
这是我的代码:
import os
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
with open("HarryPotter1.txt", 'r') as original, \
open("HarryPotter1_1.txt", 'w') as mod1, \
open("HarryPotter1_2.txt", 'w') as mod2:
data=original.read()
data_1 = data.replace("Hermione", 'Hermione_1')
data_2 = data.replace("Hermione", 'Hermione_2')
mod1.write(data_1 + r"\n")
mod2.write(data_2 + r"\n")
with open("longText.txt",'w') as longFile:
with open("HarryPotter1_1.txt",'r') as textfile:
for line in textfile:
longFile.write(line)
with open("HarryPotter1_2.txt",'r') as textfile:
for line in textfile:
longFile.write(line)
model = ""
word_vectors = ""
modelName = "ModelTest"
vectorName = "WordVectorsTestst"
answer2 = raw_input("Overwrite embeddig? (yes or n)")
if(answer2 == 'yes'):
with open("longText.txt",'r') as longFile:
sentences = []
single= []
for line in longFile:
for word in line.split(" "):
single.append(word)
sentences.append(single)
model = Word2Vec(sentences,workers=4, window=5,min_count=5)
model.save(modelName)
model.wv.save_word2vec_format(vectorName+".bin",binary=True)
model.wv.save_word2vec_format(vectorName+".txt", binary=False)
model.wv.save(vectorName)
word_vectors = model.wv
else:
model = Word2Vec.load(modelName)
word_vectors = KeyedVectors.load_word2vec_format(vectorName + ".bin", binary=True)
print(model.wv.similarity("Hermione_1","Hermione_2"))
print(model.wv.distance("Hermione_1","Hermione_2"))
print(model.wv.most_similar("Hermione_1"))
print(model.wv.most_similar("Hermione_2"))
model.wv.most_similar("Hermione_1") 和 model.wv.most_similar("Hermione_2") 怎么可能给我不同的输出?
他们的邻居完全不同。这是四个打印的输出:
0.00799602753634
0.992003972464
[('moments,', 0.3204237222671509), ('rose;', 0.3189219534397125), ('Peering', 0.3185565173625946), ('Express,', 0.31800806522369385), ('no...', 0.31678506731987), ('pushing', 0.3131707012653351), ('triumph,', 0.3116190731525421), ('no', 0.29974159598350525), ('them?"', 0.2927379012107849), ('first.', 0.29270970821380615)]
[('go?', 0.45812922716140747), ('magical', 0.35565727949142456), ('Spells."', 0.3554503619670868), ('Scabbets', 0.34701400995254517), ('cupboard."', 0.33982667326927185), ('dreadlocks', 0.3325180113315582), ('sickening', 0.32789379358291626), ('First,', 0.3245708644390106), ('met', 0.3223033547401428), ('built', 0.3218075931072235)]
【问题讨论】:
-
您确定
longText.txt有您期望的输出,尤其是\n终止行上的许多单独的句子吗? (尝试wc longText.txt并查看它。)如果它只有 1 行或很少,那么将很少进行培训。 (Word2Vec只接受带有 10,000 个标记的句子,忽略其余的。)如果您在 INFO 级别启用日志记录并在训练期间观察没有意义的进度输出,您可能还会得到提示 - 例如不反映预期的文本计数、字数或经过的时间。
标签: python string word2vec gensim word-embedding