吴恩达老师深度学习课程第五课(RNN)第二周编程作业1, 包含答案

Operations on word vectors

Welcome to your first assignment of this week!

Because word embeddings are very computionally expensive to train, most ML practitioners will load a pre-trained set of embeddings.

After this assignment you will be able to:

  • Load pre-trained word vectors, and measure similarity using cosine similarity
  • Use word embeddings to solve word analogy problems such as Man is to Woman as King is to __.
  • Modify word embeddings to reduce their gender bias

Let’s get started! Run the following cell to load the packages you will need.

import numpy as np
from w2v_utils import *

Next, lets load the word vectors. For this assignment, we will use 50-dimensional GloVe vectors to represent words. Run the following cell to load the word_to_vec_map.

words, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt')

You’ve loaded:
- words: set of words in the vocabulary.
- word_to_vec_map: dictionary mapping words to their GloVe vector representation.

You’ve seen that one-hot vectors do not do a good job cpaturing what words are similar. GloVe vectors provide much more useful information about the meaning of individual words. Lets now see how you can use GloVe vectors to decide how similar two words are.

1 - Cosine similarity

To measure how similar two words are, we need a way to measure the degree of similarity between two embedding vectors for the two words. Given two vectors uu
and v
v


, cosine similarity is defined as follows:

CosineSimilarity(u, v)=u.v||u||2||v||2=cos(θ)(1)(1)CosineSimilarity(u, v)=u.v||u||2||v||2=cos(θ)

where u.vu.v
is the dot product (or inner product) of two vectors, ||u||2||u||2
is the norm (or length) of the vector uu
, and θ
θ


is the angle between uu
and v
v


. This similarity depends on the angle between uu
and v
v


. If uu
and v
v


are very similar, their cosine similarity will be close to 1; if they are dissimilar, the cosine similarity will take a smaller value.

Figure 1: The cosine of the angle between two vectors is a measure of how similar they are

Exercise: Implement the function cosine_similarity() to evaluate similarity between word vectors.

Reminder: The norm of uu
is defined as ||u||2=ni=1u2i

|




|



u



|





|



2



=








i


=


1




n





u


i


2



# GRADED FUNCTION: cosine_similaritydef cosine_similarity(u, v):"""Cosine similarity reflects the degree of similariy between u and vArguments:u -- a word vector of shape (n,)          v -- a word vector of shape (n,)Returns:cosine_similarity -- the cosine similarity between u and v defined by the formula above."""distance = 0.0### START CODE HERE #### Compute the dot product between u and v (≈1 line)dot = np.dot(u, v)# Compute the L2 norm of u (≈1 line)norm_u = np.sqrt(np.dot(u, u))# Compute the L2 norm of v (≈1 line)norm_v = np.sqrt(np.dot(v, v))# Compute the cosine similarity defined by formula (1) (≈1 line)cosine_similarity = dot/(norm_u * norm_v)### END CODE HERE ###return cosine_similarity
father = word_to_vec_map["girl"]
mother = word_to_vec_map["boy"]
ball = word_to_vec_map["ball"]
crocodile = word_to_vec_map["crocodile"]
france = word_to_vec_map["france"]
italy = word_to_vec_map["italy"]
paris = word_to_vec_map["paris"]
rome = word_to_vec_map["rome"]print("cosine_similarity(father, mother) = ", cosine_similarity(father, mother))
print("cosine_similarity(ball, crocodile) = ",cosine_similarity(ball, crocodile))
print("cosine_similarity(france - paris, rome - italy) = ",cosine_similarity(france - paris, rome - italy))

Expected Output:

**cosine_similarity(father, mother)** = 0.890903844289
**cosine_similarity(ball, crocodile)** = 0.274392462614
**cosine_similarity(france - paris, rome - italy)** = -0.675147930817

After you get the correct expected output, please feel free to modify the inputs and measure the cosine similarity between other pairs of words! Playing around the cosine similarity of other inputs will give you a better sense of how word vectors behave.

2 - Word analogy task

In the word analogy task, we complete the sentence “a is to b as c is to __”. An example is ‘man is to woman as king is to queen’ . In detail, we are trying to find a word d, such that the associated word vectors ea,eb,ec,edea,eb,ec,ed
are related in the following manner: ebeaedeceb−ea≈ed−ec
. We will measure the similarity between ebeaeb−ea
and edeced−ec
using cosine similarity.

Exercise: Complete the code below to be able to perform word analogies!

# GRADED FUNCTION: complete_analogydef complete_analogy(word_a, word_b, word_c, word_to_vec_map):"""Performs the word analogy task as explained above: a is to b as c is to ____. Arguments:word_a -- a word, stringword_b -- a word, stringword_c -- a word, stringword_to_vec_map -- dictionary that maps words to their corresponding vectors. Returns:best_word --  the word such that v_b - v_a is close to v_best_word - v_c, as measured by cosine similarity"""# convert words to lower caseword_a, word_b, word_c = word_a.lower(), word_b.lower(), word_c.lower()### START CODE HERE #### Get the word embeddings v_a, v_b and v_c (≈1-3 lines)e_a, e_b, e_c = word_to_vec_map[word_a], word_to_vec_map[word_b], word_to_vec_map[word_c]### END CODE HERE ###words = word_to_vec_map.keys()max_cosine_sim = -100              # Initialize max_cosine_sim to a large negative numberbest_word = None                   # Initialize best_word with None, it will help keep track of the word to output# loop over the whole word vector setfor w in words:        # to avoid best_word being one of the input words, pass on them.if w in [word_a, word_b, word_c] :continue### START CODE HERE #### Compute cosine similarity between the vector (e_b - e_a) and the vector ((w's vector representation) - e_c)  (≈1 line)cosine_sim = cosine_similarity(e_b - e_a, word_to_vec_map[w] - e_c)# If the cosine_sim is more than the max_cosine_sim seen so far,# then: set the new max_cosine_sim to the current cosine_sim and the best_word to the current word (≈3 lines)if cosine_sim > max_cosine_sim:max_cosine_sim = cosine_simbest_word = w### END CODE HERE ###return best_word

Run the cell below to test your code, this may take 1-2 minutes.

triads_to_try = [('italy', 'italian', 'china'), ('india', 'delhi', 'china'), ('man', 'woman', 'boy'), ('small', 'smaller', 'big')]
for triad in triads_to_try:print ('{} -> {} :: {} -> {}'.format( *triad, complete_analogy(*triad,word_to_vec_map)))

Expected Output:

**italy -> italian** :: spain -> spanish
**india -> delhi** :: japan -> tokyo
**man -> woman ** :: boy -> girl
**small -> smaller ** :: large -> larger

Once you get the correct expected output, please feel free to modify the input cells above to test your own analogies. Try to find some other analogy pairs that do work, but also find some where the algorithm doesn’t give the right answer: For example, you can try small->smaller as big->?.

Congratulations!

You’ve come to the end of this assignment. Here are the main points you should remember:

  • Cosine similarity a good way to compare similarity between pairs of word vectors. (Though L2 distance works too.)
  • For NLP applications, using a pre-trained set of word vectors from the internet is often a good way to get started.

Even though you have finished the graded portions, we recommend you take a look too at the rest of this notebook.

Congratulations on finishing the graded portions of this notebook!

3 - Debiasing word vectors (OPTIONAL/UNGRADED)

In the following exercise, you will examine gender biases that can be reflected in a word embedding, and explore algorithms for reducing the bias. In addition to learning about the topic of debiasing, this exercise will also help hone your intuition about what word vectors are doing. This section involves a bit of linear algebra, though you can probably complete it even without being expert in linear algebra, and we encourage you to give it a shot. This portion of the notebook is optional and is not graded.

Lets first see how the GloVe word embeddings relate to gender. You will first compute a vector g=ewomanemang=ewoman−eman
, where ewomanewoman
represents the word vector corresponding to the word woman, and emaneman
corresponds to the word vector corresponding to the word man. The resulting vector gg
roughly encodes the concept of “gender”. (You might get a more accurate representation if you compute g1=emotherefather

g


1



=



e



m


o


t


h


e


r








e



f


a


t


h


e


r



, g2=egirleboyg2=egirl−eboy
, etc. and average over them. But just using ewomanemanewoman−eman
will give good enough results for now.)

g = word_to_vec_map['woman'] - word_to_vec_map['man']
print(g)

Now, you will consider the cosine similarity of different words with gg
. Consider what a positive value of similarity means vs a negative cosine similarity.

print ('List of names and their similarities with constructed vector:')# girls and boys name
name_list = ['john', 'marie', 'sophie', 'ronaldo', 'priya', 'rahul', 'danielle', 'reza', 'katy', 'yasmin']for w in name_list:print (w, cosine_similarity(word_to_vec_map[w], g))

As you can see, female first names tend to have a positive cosine similarity with our constructed vector g
g


, while male first names tend to have a negative cosine similarity. This is not suprising, and the result seems acceptable.

But let’s try with some other words.

print('Other words and their similarities:')
word_list = ['lipstick', 'guns', 'science', 'arts', 'literature', 'warrior','doctor', 'tree', 'receptionist', 'technology',  'fashion', 'teacher', 'engineer', 'pilot', 'computer', 'singer']
for w in word_list:print (w, cosine_similarity(word_to_vec_map[w], g))

Do you notice anything surprising? It is astonishing how these results reflect certain unhealthy gender stereotypes. For example, “computer” is closer to “man” while “literature” is closer to “woman”. Ouch!

We’ll see below how to reduce the bias of these vectors, using an algorithm due to Boliukbasi et al., 2016. Note that some word pairs such as “actor”/”actress” or “grandmother”/”grandfather” should remain gender specific, while other words such as “receptionist” or “technology” should be neutralized, i.e. not be gender-related. You will have to treat these two type of words differently when debiasing.

3.1 - Neutralize bias for non-gender specific words

The figure below should help you visualize what neutralizing does. If you’re using a 50-dimensional word embedding, the 50 dimensional space can be split into two parts: The bias-direction gg
, and the remaining 49 dimensions, which we’ll call g

g







. In linear algebra, we say that the 49 dimensional gg⊥
is perpendicular (or “othogonal”) to gg
, meaning it is at 90 degrees to g
g


. The neutralization step takes a vector such as ereceptionistereceptionist
and zeros out the component in the direction of gg
, giving us edebiasedreceptionist

e



r


e


c


e


p


t


i


o


n


i


s


t




d


e


b


i


a


s


e


d



.

Even though gg⊥
is 49 dimensional, given the limitations of what we can draw on a screen, we illustrate it using a 1 dimensional axis below.

Figure 2: The word vector for “receptionist” represented before and after applying the neutralize operation.

Exercise: Implement neutralize() to remove the bias of words such as “receptionist” or “scientist”. Given an input embedding ee
, you can use the following formulas to compute edebiased

e



d


e


b


i


a


s


e


d



:

ebias_component=eg||g||22g(2)(2)ebias_component=e⋅g||g||22∗g

edebiased=eebias_component(3)(3)edebiased=e−ebias_component

If you are an expert in linear algebra, you may recognize ebias_componentebias_component
as the projection of ee
onto the direction g
g


. If you’re not an expert in linear algebra, don’t worry about this.

def neutralize(word, g, word_to_vec_map):"""Removes the bias of "word" by projecting it on the space orthogonal to the bias axis. This function ensures that gender neutral words are zero in the gender subspace.Arguments:word -- string indicating the word to debiasg -- numpy-array of shape (50,), corresponding to the bias axis (such as gender)word_to_vec_map -- dictionary mapping words to their corresponding vectors.Returns:e_debiased -- neutralized word vector representation of the input "word""""### START CODE HERE #### Select word vector representation of "word". Use word_to_vec_map. (≈ 1 line)e = word_to_vec_map[word]# Compute e_biascomponent using the formula give above. (≈ 1 line)e_biascomponent = np.dot(e, g) * g /np.dot(g, g)# Neutralize e by substracting e_biascomponent from it# e_debiased should be equal to its orthogonal projection. (≈ 1 line)e_debiased = e - e_biascomponent### END CODE HERE ###return e_debiased
e = "receptionist"
print("cosine similarity between " + e + " and g, before neutralizing: ", cosine_similarity(word_to_vec_map["receptionist"], g))e_debiased = neutralize("receptionist", g, word_to_vec_map)
print("cosine similarity between " + e + " and g, after neutralizing: ", cosine_similarity(e_debiased, g))

Expected Output: The second result is essentially 0, up to numerical roundof (on the order of 101710−17
).

**cosine similarity between receptionist and g, before neutralizing:** : 0.330779417506
**cosine similarity between receptionist and g, after neutralizing:** : -3.26732746085e-17

3.2 - Equalization algorithm for gender-specific words

Next, lets see how debiasing can also be applied to word pairs such as “actress” and “actor.” Equalization is applied to pairs of words that you might want to have differ only through the gender property. As a concrete example, suppose that “actress” is closer to “babysit” than “actor.” By applying neutralizing to “babysit” we can reduce the gender-stereotype associated with babysitting. But this still does not guarantee that “actor” and “actress” are equidistant from “babysit.” The equalization algorithm takes care of this.

The key idea behind equalization is to make sure that a particular pair of words are equi-distant from the 49-dimensional gg⊥
. The equalization step also ensures that the two equalized steps are now the same distance from edebiasedreceptionistereceptionistdebiased
, or from any other work that has been neutralized. In pictures, this is how equalization works:

The derivation of the linear algebra to do this is a bit more complex. (See Bolukbasi et al., 2016 for details.) But the key equations are:

μ=ew1+ew22(4)(4)μ=ew1+ew22

μB=μbias_axis||bias_axis||22bias_axis(5)(5)μB=μ⋅bias_axis||bias_axis||22∗bias_axis

μ=μμB(6)(6)μ⊥=μ−μB

ew1B=ew1bias_axis||bias_axis||22bias_axis(7)(7)ew1B=ew1⋅bias_axis||bias_axis||22∗bias_axis

ew2B=ew2bias_axis||bias_axis||22bias_axis(8)(8)ew2B=ew2⋅bias_axis||bias_axis||22∗bias_axis

ecorrectedw1B=|1||μ||22|ew1BμB|(ew1μ)μB)|(9)(9)ew1Bcorrected=|1−||μ⊥||22|∗ew1B−μB|(ew1−μ⊥)−μB)|

ecorrectedw2B=|1||μ||22|ew2BμB|(ew2μ)μB)|(10)(10)ew2Bcorrected=|1−||μ⊥||22|∗ew2B−μB|(ew2−μ⊥)−μB)|

e1=ecorrectedw1B+μ(11)(11)e1=ew1Bcorrected+μ⊥

e2=ecorrectedw2B+μ(12)(12)e2=ew2Bcorrected+μ⊥

Exercise: Implement the function below. Use the equations above to get the final equalized version of the pair of words. Good luck!

def equalize(pair, bias_axis, word_to_vec_map):"""Debias gender specific words by following the equalize method described in the figure above.Arguments:pair -- pair of strings of gender specific words to debias, e.g. ("actress", "actor") bias_axis -- numpy-array of shape (50,), vector corresponding to the bias axis, e.g. genderword_to_vec_map -- dictionary mapping words to their corresponding vectorsReturnse_1 -- word vector corresponding to the first worde_2 -- word vector corresponding to the second word"""### START CODE HERE #### Step 1: Select word vector representation of "word". Use word_to_vec_map. (≈ 2 lines)w1, w2 = paire_w1, e_w2 = word_to_vec_map[w1], word_to_vec_map[w2]# Step 2: Compute the mean of e_w1 and e_w2 (≈ 1 line)mu = (e_w1 + e_w2)/2# Step 3: Compute the projections of mu over the bias axis and the orthogonal axis (≈ 2 lines)mu_B = np.dot(mu, bias_axis) / np.dot(bias_axis, bias_axis) * bias_axismu_orth = mu - mu_B# Step 4: Use equations (7) and (8) to compute e_w1B and e_w2B (≈2 lines)e_w1B = np.dot(e_w1, bias_axis) / np.dot(bias_axis, bias_axis) * bias_axise_w2B = np.dot(e_w2, bias_axis) / np.dot(bias_axis, bias_axis) * bias_axis# Step 5: Adjust the Bias part of e_w1B and e_w2B using the formulas (9) and (10) given above (≈2 lines)corrected_e_w1B = np.sqrt(np.abs(1-np.dot(mu_orth, mu_orth)))*(e_w1B-mu_B)/np.linalg.norm(e_w1 - mu_orth - mu_B)corrected_e_w2B = np.sqrt(np.abs(1-np.dot(mu_orth, mu_orth)))*(e_w2B-mu_B)/np.linalg.norm(e_w2 - mu_orth - mu_B)# Step 6: Debias by equalizing e1 and e2 to the sum of their corrected projections (≈2 lines)e1 = corrected_e_w1B + mu_orthe2 = corrected_e_w2B + mu_orth### END CODE HERE ###return e1, e2
print("cosine similarities before equalizing:")
print("cosine_similarity(word_to_vec_map[\"man\"], gender) = ", cosine_similarity(word_to_vec_map["man"], g))
print("cosine_similarity(word_to_vec_map[\"woman\"], gender) = ", cosine_similarity(word_to_vec_map["woman"], g))
print()
e1, e2 = equalize(("man", "woman"), g, word_to_vec_map)
print("cosine similarities after equalizing:")
print("cosine_similarity(e1, gender) = ", cosine_similarity(e1, g))
print("cosine_similarity(e2, gender) = ", cosine_similarity(e2, g))

Expected Output:

cosine similarities before equalizing:

**cosine_similarity(word_to_vec_map[“man”], gender)** = -0.117110957653
**cosine_similarity(word_to_vec_map[“woman”], gender)** = 0.356666188463

cosine similarities after equalizing:

**cosine_similarity(u1, gender)** = -0.700436428931
**cosine_similarity(u2, gender)** = 0.700436428931

Please feel free to play with the input words in the cell above, to apply equalization to other pairs of words.

These debiasing algorithms are very helpful for reducing bias, but are not perfect and do not eliminate all traces of bias. For example, one weakness of this implementation was that the bias direction gg
was defined using only the pair of words woman and man. As discussed earlier, if g
g


were defined by computing g1=ewomanemang1=ewoman−eman
; g2=emotherefatherg2=emother−efather
; g3=egirleboyg3=egirl−eboy
; and so on and averaging over them, you would obtain a better estimate of the “gender” dimension in the 50 dimensional word embedding space. Feel free to play with such variants as well.

Congratulations

You have come to the end of this notebook, and have seen a lot of the ways that word vectors can be used as well as modified.

Congratulations on finishing this notebook!

References:
- The debiasing algorithm is from Bolukbasi et al., 2016, Man is to Computer Programmer as Woman is to
Homemaker? Debiasing Word Embeddings
- The GloVe word embeddings were due to Jeffrey Pennington, Richard Socher, and Christopher D. Manning. (https://nlp.stanford.edu/projects/glove/)

Operations on word vectors-v2 吴恩达老师深度学习课程第五课第二周编程作业1相关推荐

  1. 论文整理集合 -- 吴恩达老师深度学习课程

    吴恩达老师深度学习课程中所提到的论文整理集合!这些论文是深度学习的基本知识,阅读这些论文将更深入理解深度学习. 这些论文基本都可以免费下载到,如果无法免费下载,请留言!可以到coursera中看该视频 ...

  2. Emojify - v2 吴恩达老师深度学习第五课第二周编程作业2

    吴恩达老师深度学习第五课第二周编程作业2,包含答案! Emojify! Welcome to the second assignment of Week 2. You are going to use ...

  3. 深入理解吴恩达老师深度学习课程(01神经网络和深度学习 第二周)

    深入理解吴恩达深度学习(01神经网络和深度学习 第二周) 1引言 2.1 二分类(Binary Classification) 2.1.1 符号定义(视频给出的) 2.2 逻辑回归(Logistic ...

  4. 吴恩达老师深度学习,结课了

    在2018的最后一天终于学习完了吴恩达老师深度学习课程,2018年真的收获多多,认真学完这个课程就是之一. 对于零基础,想学习深度学习的伙伴,吴恩达老师的网易深度学习微专业适合你,推荐指数4.8. 个 ...

  5. 吴恩达老师深度学习视频课笔记:总结

    吴恩达老师深度学习视频课网址为:https://mooc.study.163.com/smartSpec/detail/1001319001.htm/?utm_source=weibo.com& ...

  6. 吴恩达老师深度学习视频课笔记:逻辑回归公式推导及C++实现

    逻辑回归(Logistic Regression)是一个二分分类算法.逻辑回归的目标是最小化其预测与训练数据之间的误差.为了训练逻辑回归模型中的参数w和b,需要定义一个成本函数(cost functi ...

  7. 吴恩达Coursera深度学习课程 deeplearning.ai (4-4) 神经风格转换--编程作业

    吴恩达Coursera深度学习课程 deeplearning.ai (4-4) 神经风格转换–编程作业 注:由于这个作业目前未找到完整的中文版的,所以楼主综合了几篇不完整的,自己完整运行了一遍(pyt ...

  8. 吴恩达老师深度学习视频课笔记:自然语言处理与词嵌入

    Word representation:词嵌入(word embedding),是语言表示的一种方式,可以让算法自动理解一些类似的词比如男人.女人,国王.王后等.通过词嵌入的概念,即使你的模型标记的训 ...

  9. 吴恩达Coursera深度学习课程 deeplearning.ai (5-2) 自然语言处理与词嵌入--编程作业(二):Emojify表情包

    Part 2: Emojify 欢迎来到本周的第二个作业,你将利用词向量构建一个表情包. 你有没有想过让你的短信更具表现力? emojifier APP将帮助你做到这一点. 所以不是写下"C ...

最新文章

  1. 企业网络推广期间影响企业网络推广自然排名的因素有哪些?
  2. 原生js监听input值发生变化
  3. MATLAB数据处理快速学习教程
  4. 09945 oracle 解决方法_ORACLE rman与RMAN-00054ORA-09945
  5. Boost::context模块callcc的回溯测试程序
  6. spring cloud 微服务相关信息
  7. android透明activity,Android 简单实现透明Activity
  8. Spring Boot 是什么,有什么用。
  9. hihocoder第233周
  10. JavaScript:画廊案例
  11. java项目代码加密
  12. c语言用串口读温度值,温度传感器与串口
  13. 大学毕业生推荐表的计算机水平,大学毕业生就业推荐表学校鉴定评语
  14. OPEN-WRT老毛子固件的无线中继设置建议
  15. 技术经理成长复盘-聊聊核心骨干
  16. uniapp小程序发布过程中,图片跟音频资源超过200K无法上传
  17. Ant Design Pro V4下载运行
  18. QPainter 绘制的旋转中心问题
  19. 2022年计算机考研数学一真题(网友版)
  20. linux系统make命令详解

热门文章

  1. python实现tcp发包_python 多线程tcp udp发包 Dos工具。
  2. java 正则 反向引用_正则之反向引用
  3. 7-12 两个数的简单计算器 (C语言)
  4. 求表达式1-1/2+1/3-1/4+1/5-1/6+1/7-...+1/n的值
  5. qt获取console输出_怎么在Centos 7 安装 Qt-4.8.6-MySQL 驱动?
  6. 新手学习python的方法
  7. 国内三分之一世界500强企业正布局区块链,区块链风口已经出现
  8. 怎样实现基于Trie树和字典的分词功能
  9. C语言基础知识【常量】
  10. 云服务蓬勃发展,平均年增长率高达28%