如何可视化word2vec单词向量?
0 1297
2
该提问暂无详细描述
收藏
2021-01-26 15:08 更新 天明 •  1290
共 1 个回答
高赞 时间
0

你可以使用t-SNE:这是一种降维技术,可用于可视化高维向量,例如单词嵌入。 下面是一个使用Scikit-learn的Python示例代码。 它上传一个文本格式的预训练的嵌入文件,应用了t-SNE算法并将单词可视化。

import sys 
import codecs 
import numpy as np 
import matplotlib.pyplot as plt 
 
from sklearn.manifold import TSNE 
 
 
def main(): 
 
    embeddings_file = sys.argv[1] 
    wv, vocabulary = load_embeddings(embeddings_file) 
 
    tsne = TSNE(n_components=2, random_state=0) 
    np.set_printoptions(suppress=True) 
    Y = tsne.fit_transform(wv[:1000,:]) 
 
    plt.scatter(Y[:, 0], Y[:, 1]) 
    for label, x, y in zip(vocabulary, Y[:, 0], Y[:, 1]): 
        plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords='offset points') 
    plt.show() 
 
 
def load_embeddings(file_name): 
 
    with codecs.open(file_name, 'r', 'utf-8') as f_in: 
        vocabulary, wv = zip(*[line.strip().split(' ', 1) for line in  
f_in]) 
    wv = np.loadtxt(wv) 
    return wv, vocabulary 
 
if __name__ == '__main__': 
    main() 

由于内存问题,我仅将其应用于前1000个单词。 这是我的结果(我使用了50维预训练的GloVe词嵌入):

这是一个放大图:

收藏
2021-01-26 15:28 更新 Lisa •  1796