本文是基于吴恩达老师《深度学习》第五课第二周练习题所做。
0.背景简介
由于词向量的训练需要花费大量的计算,因此本文直接load预先训练好的词向量,在辅助程序中使用read_glove_vecs()函数从glove.6B.50d.txt中导入。
def read_glove_vecs(glove_file):
with open(glove_file, 'r', encoding = 'utf-8') as f:
words = set()
word_to_vec_map = {}
for line in f:
line = line.strip().split()
curr_word = line[0]
words.add(curr_word)
word_to_vec_map[curr_word] = np.array(line[1:], dtype=np.float64)
return words, word_to_vec_map
文本所需的第三方库及辅助程序,可点击此处下载。
import numpy as np
from w2v_utils import *
words, word_to_vec_map = read_glove_vecs('data\glove.6B.50d.txt')
其实GloVe向量集为我们提供了更多的有用的信息,首先我们来分析一下如何确定两个词之间的相似性。
1.余弦相似度
为了衡量两个向量间的相似度,我们采用余弦相似度的定义,其实质就是计算两个向量的余弦值,直观的理解就是使用向量间的夹角大小来衡量二者的相似性。计算公式及原理图如下。
其中:
def cosine_similarity(u, v):
distance = 0
dot = np.dot(u, v)
norm_u = np.sqrt(np.sum(u ** 2))
norm_v = np.sqrt(np.sum(v ** 2))
cosine_similarity = dot / (norm_u * norm_v)
return cosine_similarity
father = word_to_vec_map[b"father"]
mother = word_to_vec_map[b"mother"]
ball = word_to_vec_map[b"ball"]
crocodile = word_to_vec_map[b"crocodile"]
france = word_to_vec_map[b"france"]
italy = word_to_vec_map[b"italy"]
paris = word_to_vec_map[b"paris"]
rome = word_to_vec_map[b"rome"]
print("cosine_similarity(father, mother) = ", cosine_similarity(father, mother))
print("cosine_similarity(ball, crocodile) = ",cosine_similar