gensim 训练和持久化,保存到文件,读取模型

gensim 训练和持久化,保存到文件,读取模型


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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)

Be the first to comment

Leave a Reply

Your email address will not be published.