词向量的优化操作

本文探讨了词向量的优化,包括使用余弦相似度评估词的相似性,进行词类比任务,并通过中立化偏差和性别相关词对的均衡方法减少词向量中的偏见。介绍了GloVe向量与性别关联的分析,以及词向量除偏的数学原理和方法。
摘要由CSDN通过智能技术生成

本文是基于吴恩达老师《深度学习》第五课第二周练习题所做。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值