gensim 训练和持久化,保存到文件,读取模型
import gensim
import numpy as np
import tensorflow as tf
from numpy import linalg as la
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey"]
# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
print(texts)
# remove words that appear only once
from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token] += 1
texts = [[token for token in text if frequency[token] > 1] for text in texts]
# build the same model, making the 2 steps explicit
new_model = gensim.models.Word2Vec(min_count=1) # an empty model, no training
new_model.build_vocab(texts) # can be a non-repeatable, 1-pass generator
new_model.train(texts, total_examples=new_model.corpus_count, epochs=new_model.iter)
new_model.save("computer.txt")
model = gensim.models.Word2Vec.load("computer.txt")
print(model["computer"].shape)