gensim(四)--word2vec embedding

训练并保存模型

def train_savemodel():
    model = Word2Vec(PathLineSentences(directory), size=400, window=5, min_count=5, workers=multiprocessing.cpu_count(),
                     sg=1,  # 使用 skip-gram算法
                     hs=1,  # 使用分层softmax
                     negative=0)  # 不使用负采样和噪音
    model.save(modelpath)
    model.wv.save_word2vec_format(wv_path, binary=True)

加载模型

def loadmodel():
    en_wiki_word2vec_model = Word2Vec.load(modelpath)
    return en_wiki_word2vec_model

加载wv,如果不需要再次训练模型,那么只需要恢复wv就可以了,wv是去除了model中的权重参数和损失等细节的,可以直接用于查询。

def loadwv():
    word_vectors = KeyedVectors.load_word2vec_format(wv_path, binary=True)
    return word_vectors

打印每一个词以及他的相近的词

most_similars_pre = {word : md.wv.most_similar(word) for word in md.wv.index2word}
    for i, (key,word) in enumerate(most_similars_pre.items()):
        if i == 10:
            break
        print(key,word)

使用TSNE降维(这个操作很费时间),打印关系图:

def reduce_dimensions(model):
    num_dimensions=2
    vectors =[]
    labels = []
    for word in model.wv.vocab:
        vectors.append(model.wv[word])
        labels.append(word)
    vectors=np.asarray(vectors)
    labels =np.asarray(labels)
    #使用t-sne降低维度
    vectors=np.asarray(vectors)
    tsne =TSNE(n_components=num_dimensions, random_state=0)
    vectors = tsne.fit_transform(vectors)

    x_vals =[v[0] for v in vectors]
    y_vals =[v[1] for v in vectors]
    return x_vals,y_vals,labels
def plot_with_plotly(x_vals, y_vals, labels, plot_in_notebook=True):
    from plotly.offline import init_notebook_mode,iplot,plot
    import plotly.graph_objs as go

    trace =go.Scatter(x=x_vals,y=y_vals,mode='text',text=labels)
    data = [trace]

    if plot_in_notebook:
        init_notebook_mode(connected=True)
        iplot(data,filename='word-embedding-plot')
    else:
        plot(data, filename='word-embedding-plot.html')

def plot_with_matplotlib(x_vals, y_vals, labels):
    import matplotlib.pyplot as plt
    import random

    random.seed(0)
    plt.figure(figsize=(12,12))
    plt.scatter(x_vals,y_vals)

    indices =list(range(len(labels)))
    selected_indices = random.sample(indices,25)
    for i in selected_indices:
        plt.annotate(labels[i], (x_vals[i],y_vals[i]))
    plt.show()
 x_vals, y_vals, labels =reduce_dimensions(md)
    try:
        get_ipython()
    except Exception:
        plot_function = plot_with_matplotlib
    else:
        plot_function = plot_with_plotly
    plot_function(x_vals,y_vals,labels)

跑了半个小时的一张图
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值