gensim将python dict字典形式的词向量导入到word2vec模型(同时适合gensim4.0+版本)

先上代码,解释在后:

代码

注意:本代码的gensim 版本适合4.0.0及以上,低于此版本的代码请参考:https://stackoverflow.com/questions/45981305/convert-python-dictionary-to-word2vec-object

import numpy as np
from gensim import utils
from numpy import float32 as REAL
import gensim  # '4.0.1'


def my_save_word2vec_format(file_name, word2veckeyedVector, binary=True):
    total_vec = len(word2veckeyedVector.index_to_key)  # 全部的单词数
    with utils.open(file_name, 'wb') as fout:
        print(total_vec, word2veckeyedVector.vector_size)
        fout.write(utils.to_utf8("%s %s\n" % (total_vec, word2veckeyedVector.vector_size)))
        # store in sorted order: most frequent words at the top
        for key in word2veckeyedVector.index_to_key:
            value = word2veckeyedVector.get_vector(key)
            if binary:
                value = value.astype(REAL)
                fout.write(utils.to_utf8(key) + b" " + value.tobytes())
            else:
                fout.write(utils.to_utf8("%s %s\n" % (key, ' '.join(repr(val) for val in value))))


if __name__ == '__main__':
    # ============步骤1:构建一个字典,这个字典可以是你的预训练模型,key就是你的词,value就是词向量============
    d = {}
    d['a'] = np.random.randn(300)
    d['b'] = np.random.randn(300)
    # ============步骤2:构建词向量Word2VecKeyedVectors============
    m = gensim.models.keyedvectors.Word2VecKeyedVectors(vector_size=300)  # 注意这里要和词向量的长度相等
    m.add_vectors(list(d.keys()), list(d.values()))  # 把我们的字典加入到空的词向量中
    # ============步骤3:将Word2VecKeyedVectors导出到标准的word2vec_format格式的文件中============
    my_save_word2vec_format(file_name='train.bin', word2veckeyedVector=m)

    # ============================================================
    # ============然后就OK啦,下面是读取并导入模型的测试===============
    # ============================================================
    # ============读取方式1:keyedvectors============
    m2 = gensim.models.keyedvectors.Word2VecKeyedVectors.load_word2vec_format('train.bin', binary=True)
    print(m2.vectors == m.vectors)
    # ============读取方式2:Word2Vec============
    from gensim.models import Word2Vec

    word2vec_model = Word2Vec().wv.load_word2vec_format('train.bin', binary=True)

解释

大致的思路:

  1. dict文件目前并不能直接导入到模型中。目前手续就是比较繁琐,需要的步骤:
    python 字典->Word2VecKeyedVectors-> Word2Vec
  2. Word2VecKeyedVectorsWord2Vec的区别是:
  • Word2VecKeyedVectors不能继续增量训练,但是执行效率会超级高
  • Word2Vec常用Word2vec.wv.xxxxx这种函数,可以接着增量训练,但是查询词向量等效率要低一些
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值