【word2vec】之 训练模型结果的结构探究 模型改造 python gensim

word2vec的安装,应用帖子好多,那如果想在训练的结果,也就是得到的向量上做点儿文章,该如何呢

下面来说说word2vec(python的gensim包)训练得到的模型,以及得到的向量是什么样子的

因为python训练得到的结果是二进制的,说白了就是乱码,现在既然想得到整个结果,该怎么弄呢。

其实好多事情直接看源码就能得到。之前试图找api或者小伙伴的帖子,想看看model的结构是什么样子的,未遂,只好直接自己一点儿点儿看源码。

首先我们假设,已经训练好了一个模型,现在只需要load就行了

model gensim.models.Word2Vec.load('/mymodel_wds_wiki_all')


首先,获得一个词的词向量可以直接通过这样的方式获得

print len(model['中国'])
print type(model['中国'])
print (model['中国'])


得到的结果如下,可见类型是numpy.ndarray,维度是默认的一百维

100

<type 'numpy.ndarray'>

[-1.36747932  1.64107883  2.22578478 -2.02663827  3.4452529   1.86765969 ……]


下面直接看model的代码


self.vocab {}  # mapping from a word (string) to a Vocab object
self.index2word []  # map from a word's matrix index (int) to word (string)
self.sg int(sg)
self.cum_table None  # for negative sampling
self.vector_size int(size)
self.layer1_size int(size)
if size != 0:
    logger.warning("consider setting layer size to a multiple of 4 for greater performance")
self.alpha float(alpha)
self.window int(window)
self.max_vocab_size max_vocab_size
self.seed seed
self.random random.RandomState(seed)
self.min_count min_count
self.sample sample
self.workers int(workers)
self.min_alpha float(min_alpha)
self.hs hs
self.negative negative
self.cbow_mean int(cbow_mean)
self.hashfxn hashfxn
self.iter iter
self.null_word null_word
self.train_count 0
self.total_train_time 0
self.sorted_vocab sorted_vocab
self.batch_words batch_words


这里面可以看到,词都存在了vocab {} 这个字典里

那我们来访问一下试试

for k,in model.vocab.items():
    print k,v

得到如下结果

义演 Vocab(count:106, index:70231, sample_int:4294967296L)
佳酿 Vocab(count:16, index:224970, sample_int:4294967296L)
群落生境 Vocab(count:28, index:166480, sample_int:4294967296L)
黑变病 Vocab(count:336, index:32138, sample_int:4294967296L)
行房 Vocab(count:34, index:144120, sample_int:4294967296L)
集美 Vocab(count:258, index:38457, sample_int:4294967296L)
视锐度 Vocab(count:32, index:152414, sample_int:4294967296L)
设军 Vocab(count:10, index:308955, sample_int:4294967296L)
呼格 Vocab(count:110, index:68738, sample_int:4294967296L)

这个index应该就是在model里面的一个坐标
count表示在整个语料中,这个词出现的次数

如果改成这句话,得到的结果是一样的

print k,model.vocab[k]


这样,通过遍历整个vocab,就能得到全部的表示成

【词 向量】 x n

的结果了


可以使用下面的代码

def generateTrainedModel(filename,num):
    output open(filename'w')
    count 0
    content str(num' 200\n'
    for k,in model.vocab.items():
        # print k,type(model[k].tolist())
       (model[k].tolist())
        content += str(k) ' '
        for in l:
            content += str(i) ' '
        for in l[:-1]:
            content += str(i) ' '
        content += str(l[-1])
        content += '\n'
    # content.encode('utf-8')
    output.write(content[:-2])
    output.close()



那这个结果保存成文件之后怎么加载呢?
可以通过这个语句,直接binary指定是不是二进制文件,来确定

model.save_word2vec_format('C:\Users\nnn\Desktop\Word2Vec\\test.txt', binary=False)


这样一来,就可以改造word2vec的训练结果了



猜你喜欢

转载自blog.csdn.net/sscssz/article/details/51921392