直接上代码吧,word2vec
# test from gensim.models.word2vec import Word2Vec txt_file = open('data.txt') sentences = [] line = txt_file.readline() while line: sentence = line.split(' ') sentences.append(sentence) line = txt_file.readline() model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=1) model.save('model_word2vec.model') model_use = Word2Vec.load('model_word2vec.model') xx = model_use.wv.vocab # print(model_use.wv.vocab) print('hel') print(model_use.most_similar('nice')) print(model_use.wv.similarity('nice', 'great'))
各种参数详解:
https://www.cnblogs.com/pinard/p/7278324.html
模型的一些其他使用:
https://blog.csdn.net/qq_19707521/article/details/79169826
自己在使用中:
from gensim.models import Word2Vec from gensim.models import KeyedVectors if file_to_load is not None: # 这种方法加载是加载.model文件,好处是可以再次训练 # w2vModel = Word2Vec.load(file_to_load) # 这种方法是加载.txt文件,好处是model.txt文件里面可以可视化地看每一个单词对应的向量 w2vModel = KeyedVectors.load_word2vec_format(file_to_load) print(w2vModel.most_similar("开心")) else: w2vModel = Word2Vec(sentences, size = embedding_size, window = window, min_count = min_count, workers = multiprocessing.cpu_count()) if file_to_save is not None: # 这种方法就是保存的.model文件 # w2vModel.save(file_to_save) # 这种方法就是保存的.txt文件,注意指定文件名是xxxxx.txt w2vModel.wv.save_word2vec_format(file_to_save, binary=False)
需要注意的一点就是.txt文件可以看到在第一行是这样的
25019 100
第一个表明word2vec里面的单词数,第二个100表示维度。
如果加载其他的方法训练出来的.txt文件,或者说自己瞎捣鼓出来的词向量.txt文件,想用gensim来加载,那么一定要注意第一行的问题。