文章目录

  • 1 - 词向量运算
    • 1.1 - 余弦相似度
    • 1.2 - 词类类比
    • 1.3 - 去除词向量中的偏见(选学)
      • 1.3.1 - 消除与性别无关的词汇的偏差
      • 1.3.2 - 性别词的均衡算法
  • 2 - Emoji表情生成器
    • 2.1 - 基准模型:Emojifier - V1
      • 2.1.1 数据集
      • 2.1.2 - Emojifier-V1的结构
      • 2.1.3 - 实现Emojifier-V1
      • 2.1.4 - 验证集
    • 2.2 - Emojifier-V2:在Keras中使用LSTM模块
      • 2.2.1 - 模型预览
      • 2.2.2 - Keras与mini-batching
      • 2.2.3 - 嵌入层( The Embedding layer)
    • 2.3 - 构建Emojifier-V2

1 - 词向量运算

因为词嵌入的训练是非常耗资源的,所以大部分人都是选择加载训练好的词嵌入数据。在本博客中,我们将学习到:

  1. 如何加载训练好了的词向量
  2. 使用余弦相似性计算相似度
  3. 使用词嵌入来解决“男人与女人相比就像国王与__相比”之类的词语类比问题
  4. 修改词嵌入以减少性别偏见等
import numpy as np
import w2v_utils

接下来就是加载词向量了,这里我们使用50维的向量来表示单词:

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

我们加载了以下数据:

  • words:单词的集合
  • word_to_vec_map:字典类型,单词到GloVe向量的映射
# python 3.x
print(word_to_vec_map['hello'])
[-0.38497   0.80092   0.064106 -0.28355  -0.026759 -0.34532  -0.64253-0.11729  -0.33257   0.55243  -0.087813  0.9035    0.47102   0.566570.6985   -0.35229  -0.86542   0.90573   0.03576  -0.071705 -0.123270.54923   0.47005   0.35572   1.2611   -0.67581  -0.94983   0.686660.3871   -1.3492    0.63512   0.46416  -0.48814   0.83827  -0.9246-0.33722   0.53741  -1.0616   -0.081403 -0.67111   0.30923  -0.3923-0.55002  -0.68827   0.58049  -0.11626   0.013139 -0.57654   0.0488330.67204 ]

因为独热向量不能很好地表示词与词之间的相似性,所以使用了GlovVel向量,它保存了每个单词更多、更有用的信息,我们现在可以看到如何比较两个词的相似性

1.1 - 余弦相似度


图1-1:两个向量之间的夹角余弦值用来衡量它们的相似程度

接下来我们要实现一个计算两个词的相似度的函数cosine_similarity()

提醒:u的范数是这样定义的:∣∣u∣∣2=∑i=1nui2||u||_2 = \sqrt{\sum_{i=1}^n u_i^2}∣∣u2=i=1nui2

def cosine_similarity(u, v):"""u与v的余弦相似度反映了u与v的相似程度参数:u -- 维度为(n,)的词向量v -- 维度为(n,)的词向量返回:cosine_similarity -- 由上面公式定义的u和v之间的余弦相似度。"""distance = 0# 计算u与v的内积dot = np.dot(u, v)#计算u的L2范数norm_u = np.sqrt(np.sum(np.power(u, 2)))#计算v的L2范数norm_v = np.sqrt(np.sum(np.power(v, 2)))# 根据公式1计算余弦相似度cosine_similarity = np.divide(dot, norm_u * norm_v)return cosine_similarity
father = word_to_vec_map["father"]
mother = word_to_vec_map["mother"]
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))
cosine_similarity(father, mother) =  0.8909038442893615
cosine_similarity(ball, crocodile) =  0.27439246261379424
cosine_similarity(france - paris, rome - italy) =  -0.6751479308174202

当然你也可以随意修改其他词汇,然后看看它们只的相似性

1.2 - 词类类比

在这里,我们将学习解决“A与B相比就类似于C与____ 相比一样”之类的问题,打个比方,“男人与女人相比就像国王与 女皇 相比”。实际上我们需要找到一个词d,然后ea,eb,ec,ede_a,e_b,e_c,e_dea,eb,ec,ed满足以下关系:eb−ea≈ed−ece_b-e_a ≈ e_d-e_cebeaedec,当然eb−eae_b-e_aebeaed−ece_d-e_cedec是使用余弦相似性来判断的

def complete_analogy(word_a, word_b, word_c, word_to_vec_map):"""解决“A与B相比就类似于C与____相比一样”之类的问题参数:word_a -- 一个字符串类型的词word_b -- 一个字符串类型的词word_c -- 一个字符串类型的词word_to_vec_map -- 字典类型,单词到GloVe向量的映射返回:best_word -- 满足(v_b - v_a) 最接近 (v_best_word - v_c) 的词"""# 把单词转换为小写word_a, word_b, word_c = word_a.lower(), word_b.lower(), word_c.lower()# 获取对应单词的词向量e_a, e_b, e_c = word_to_vec_map[word_a], word_to_vec_map[word_b], word_to_vec_map[word_c]# 获取全部的单词words = word_to_vec_map.keys()# 将max_cosine_sim初始化为一个比较大的负数max_cosine_sim = -100best_word = None# 遍历整个数据集for word in words:# 要避免匹配到输入的数据if word in [word_a, word_b, word_c]:continue# 计算余弦相似度cosine_sim = cosine_similarity((e_b - e_a), (word_to_vec_map[word] - e_c))if cosine_sim > max_cosine_sim:max_cosine_sim = cosine_simbest_word = wordreturn best_word
triads_to_try = [('italy', 'italian', 'spain'), ('india', 'delhi', 'japan'), ('man', 'woman', 'boy'), ('small', 'smaller', 'large')]
for triad in triads_to_try:print ('{} -> {} <====> {} -> {}'.format( *triad, complete_analogy(*triad,word_to_vec_map)))
italy -> italian <====> spain -> spanish
india -> delhi <====> japan -> tokyo
man -> woman <====> boy -> girl
small -> smaller <====> large -> larger

可以随意地去更改上面的词汇,看看能否拿到自己期望的输出,你也可以试试能不能让程序出一点小错呢?比如:small -> smaller <===> big -> ? ,自己试试呗~

triads_to_try = [('small', 'smaller', 'big')]
for triad in triads_to_try:print ('{} -> {} <====> {} -> {}'.format( *triad, complete_analogy(*triad,word_to_vec_map)))
small -> smaller <====> big -> competitors

现在词类类比已经完成了,需要记住的是余弦相似度是比较词向量相似度的一种好方法,尽管使用L2距离(欧式距离)来比较也是可以的

1.3 - 去除词向量中的偏见(选学)

在这一部分,我们将研究反映在词嵌入中的性别偏差,并试着去去除这一些偏差,除了学习这个内容外,这一节还可以磨炼你对单词向量的直觉,这部分包含有线性代数,不是很难,如果你没有学习过线性代数,那么你可以跳过这一节,你也可以继续深入下去

我们首先来看一下包含在词嵌入中的性别偏差,我们首先计算一下g=ewoman−emang = e_{woman}-e_{man}g=ewomaneman,其中ewomane_{woman}ewoman是单词"woman"对应的词向量,emane_{man}eman是单词"man"对应的词向量,得到的结果g粗略的包含了性别这一概念,但是如果你计算g1=emother−efatherg_1=e_{mother}-e_{father}g1=emotherefatherg2=egirl−eboyg_2=e_{girl}-e_{boy}g2=egirleboy的平均值,可能会更准确一点,但是在这里,ewoman−emane_{woman}-e_{man}ewomaneman就已经足够了

g = word_to_vec_map['woman'] - word_to_vec_map['man']
print(g)
[-0.087144    0.2182     -0.40986    -0.03922    -0.1032      0.94165-0.06042     0.32988     0.46144    -0.35962     0.31102    -0.868240.96006     0.01073     0.24337     0.08193    -1.02722    -0.211220.695044   -0.00222     0.29106     0.5053     -0.099454    0.404450.30181     0.1355     -0.0606     -0.07131    -0.19245    -0.06115-0.3204      0.07165    -0.13337    -0.25068714 -0.14293    -0.224957-0.149       0.048882    0.12191    -0.27362    -0.165476   -0.204260.54376    -0.271425   -0.10245    -0.32108     0.2516     -0.33455-0.04371     0.01258   ]

现在,我们不考虑不同单词与g的余弦相似度,考虑相似度的正值与余弦值的负值之间的关系

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))
john -0.23163356145973724
marie 0.315597935396073
sophie 0.31868789859418784
ronaldo -0.3124479685032943
priya 0.17632041839009402
rahul -0.16915471039231722
danielle 0.24393299216283892
reza -0.07930429672199552
katy 0.2831068659572615
yasmin 0.23313857767928758

正如我们所看见的,女性的名字与g的与余弦相似度为正,而男性为负,这也不出乎人的意料,我们来看看其他词

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))
lipstick 0.2769191625638266
guns -0.1888485567898898
science -0.060829065409296994
arts 0.008189312385880328
literature 0.06472504433459927
warrior -0.20920164641125288
doctor 0.11895289410935041
tree -0.07089399175478091
receptionist 0.33077941750593737
technology -0.13193732447554296
fashion 0.03563894625772699
teacher 0.17920923431825664
engineer -0.08039280494524072
pilot 0.0010764498991916787
computer -0.10330358873850498
singer 0.1850051813649629

发现了吗?比如“computer”就接近于“man”,“literature ”接近于“woman”,但是这些都是不对的一些观念,那么我们该如何减少这些偏差呢?

对于一些特殊的词汇而言,比如“男演员(actor)”与“女演员(actress)”或者“祖母(grandmother)”与“祖父(grandfather)”之间应该是具有性别差异的,但是其他的词汇比如“接待员(receptionist)”与“技术(technology )”是不应该有性别差异的,当我们处理这些词汇的时候应该区别对待

1.3.1 - 消除与性别无关的词汇的偏差


图1-2:单词"recptionist"在消除性别偏差前后的示意图

现在我们要实现neutralize()函数来消除包含在词汇向量里面的性别偏差,给定一个输入:词嵌入(embedding)e,那么我们可以使用下面的公式计算edebiasede^{debiased}edebiased

def neutralize(word, g, word_to_vec_map):"""通过将“word”投影到与偏置轴正交的空间上,消除了“word”的偏差。该函数确保“word”在性别的子空间中的值为0参数:word -- 待消除偏差的字符串g -- 维度为(50,),对应于偏置轴(如性别)word_to_vec_map -- 字典类型,单词到GloVe向量的映射返回:e_debiased -- 消除了偏差的向量。"""# 根据word选择对应的词向量e = word_to_vec_map[word]# 根据公式2计算e_biascomponente_biascomponent = np.divide(np.dot(e, g), np.square(np.linalg.norm(g))) * g# 根据公式3计算e_debiasede_debiased = e - e_biascomponentreturn e_debiased
e = "receptionist"
print("去偏差前{0}与g的余弦相似度为:{1}".format(e, cosine_similarity(word_to_vec_map["receptionist"], g)))e_debiased = neutralize("receptionist", g, word_to_vec_map)
print("去偏差后{0}与g的余弦相似度为:{1}".format(e, cosine_similarity(e_debiased, g)))
去偏差前receptionist与g的余弦相似度为:0.33077941750593737
去偏差后receptionist与g的余弦相似度为:1.1682064664487028e-17

请注意:你的第二个结果可能与我不一样,但基本上是接近于0的(10−17)(10^{-17})(1017)

1.3.2 - 性别词的均衡算法

接下来我们来看看在关于有特定性别词组中,如何将它们进行均衡,比如“男演员”与“女演员”中,与“保姆”一词更接近的是“女演员”,我们可以消去“保姆”的性别偏差,但是这并不能保证“保姆”一词与“男演员”与“女演员”之间的距离相等,我们要学的均衡算法将解决这个问题

均衡算法背后的关键思想是确保一对特定的单词与49维的g⊥g_⊥g距离相等

线性代数的推导过程要复杂很多(细节见Bolukbasi et al., 2016),但是关键方程如下:

def equalize(pair, bias_axis, word_to_vec_map):"""通过遵循上图中所描述的均衡方法来消除性别偏差。参数:pair -- 要消除性别偏差的词组,比如 ("actress", "actor") bias_axis -- 维度为(50,),对应于偏置轴(如性别)word_to_vec_map -- 字典类型,单词到GloVe向量的映射返回:e_1 -- 第一个词的词向量e_2 -- 第二个词的词向量"""# 第1步:获取词向量w1, w2 = paire_w1, e_w2 = word_to_vec_map[w1], word_to_vec_map[w2]# 第2步:计算w1与w2的均值mu = (e_w1 + e_w2) / 2.0# 第3步:计算mu在偏置轴与正交轴上的投影mu_B = np.divide(np.dot(mu, bias_axis), np.square(np.linalg.norm(bias_axis))) * bias_axismu_orth = mu - mu_B# 第4步:使用公式7、8计算e_w1B 与 e_w2Be_w1B = np.divide(np.dot(e_w1, bias_axis), np.square(np.linalg.norm(bias_axis))) * bias_axise_w2B = np.divide(np.dot(e_w2, bias_axis), np.square(np.linalg.norm(bias_axis))) * bias_axis# 第5步:根据公式9、10调整e_w1B 与 e_w2B的偏置部分corrected_e_w1B = np.sqrt(np.abs(1-np.square(np.linalg.norm(mu_orth)))) * np.divide(e_w1B-mu_B, np.abs(e_w1 - mu_orth - mu_B))corrected_e_w2B = np.sqrt(np.abs(1-np.square(np.linalg.norm(mu_orth)))) * np.divide(e_w2B-mu_B, np.abs(e_w2 - mu_orth - mu_B))# 第6步: 使e1和e2等于它们修正后的投影之和,从而消除偏差e1 = corrected_e_w1B + mu_orthe2 = corrected_e_w2B + mu_orthreturn e1, e2
print("==========均衡校正前==========")
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))
e1, e2 = equalize(("man", "woman"), g, word_to_vec_map)
print("\n==========均衡校正后==========")
print("cosine_similarity(e1, gender) = ", cosine_similarity(e1, g))
print("cosine_similarity(e2, gender) = ", cosine_similarity(e2, g))
==========均衡校正前==========
cosine_similarity(word_to_vec_map["man"], gender) =  -0.1171109576533683
cosine_similarity(word_to_vec_map["woman"], gender) =  0.3566661884627037==========均衡校正后==========
cosine_similarity(e1, gender) =  -0.7165727525843935
cosine_similarity(e2, gender) =  0.7396596474928908

2 - Emoji表情生成器

在这里,我们要学习使用词向量来构建一个表情生成器

你有没有想过让你的文字也有更丰富表达能力呢?比如写下“Congratulations on the promotion! Lets get coffee and talk. Love you!”,那么你的表情生成器就会自动生成“Congratulations on the promotion! ? Lets get coffee and talk. ☕️ Love you! ❤️”

另一方面,如果你对这些表情不感冒,而你的朋友给你发了一大堆的带表情的文字,那么你也可以使用表情生成器来怼回去

我们要构建一个模型,输入的是文字(比如“Let’s go see the baseball game tonight!”),输出的是表情(⚾️)。在众多的Emoji表情中,比如“❤️”代表的是“心”而不是“爱”,但是如果你使用词向量,那么你会发现即使你的训练集只明确地将几个单词与特定的表情符号相关联,你的模型也了能够将测试集中的单词归纳、总结到同一个表情符号,甚至有些单词没有出现在你的训练集中也可以

在这里,我们将开始构建一个使用词向量的基准模型(Emojifier-V1),然后我们会构建一个更复杂的包含了LSTM的模型(Emojifier-V2)

请注意:你可能需要运行pip install emoji命令来获取emoji包

import numpy as np
import emo_utils
import emoji
import matplotlib.pyplot as plt
import importlib
importlib.reload(emo_utils)%matplotlib inline

2.1 - 基准模型:Emojifier - V1

2.1.1 数据集

我们来构建一个简单的分类器,首先是数据集(X,Y):

  • X:包含了127个字符串类型的短句
  • Y:包含了对应短句的标签(0 - 4)
图2-1:EMOJISET - 5类分类问题,这里给出了几个例子

现在我们来加载数据集,训练集:127,测试集:56

X_train, Y_train = emo_utils.read_csv('data/train_emoji.csv')
X_test, Y_test = emo_utils.read_csv('data/test.csv')maxLen = len(max(X_train, key=len).split())

你可以随意更改index的值来看看训练集里面到底有什么东西,使用jupyter notebook的用户需要注意的是,由于字体原因,你打印出来的心有可能是黑色的,但是没有任何问题

index  = 3
print(X_train[index], emo_utils.label_to_emoji(Y_train[index]))
Miss you so much ❤️

2.1.2 - Emojifier-V1的结构

在这里,我们要实现一个叫“Emojifier-V1”的基准模型

图2-2:基准模型(Emojifier-V1)

模型的输入是一段文字(比如“l lov you”),输出的是维度为(1,5)的向量,最后在argmax层找寻最大可能性的输出

现在我们将我们的标签Y YY转换成softmax分类器所需要的格式,即从(m,1)转换为独热编码(m,5),每一行都是经过编码后的样本,其中Y_oh指的是“Y-one-hot”

Y_oh_train = emo_utils.convert_to_one_hot(Y_train, C=5)
Y_oh_test = emo_utils.convert_to_one_hot(Y_test, C=5)

当然,你也可以改变index的值来看看独热编码

index = 0
print("{0}对应的独热编码是{1}".format(Y_train[index], Y_oh_train[index]))
3对应的独热编码是[0. 0. 0. 1. 0.]

数据集准备好了,现在我们就来实现这个模型

2.1.3 - 实现Emojifier-V1

正如图2-2所示,第一步就是把输入的句子转换为词向量,然后获取均值,我们依然使用50维的词嵌入,现在我们加载词嵌入:

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

我们加载了:

  • word_to_index:字典类型的词汇(400,001个)与索引的映射(有效范围:0-400,000)
  • index_to_word:字典类型的索引与词汇之间的映射
  • word_to_vec_map:字典类型的词汇与对应GloVe向量的映射
word = "cucumber"
index = 113317
print("单词{0}对应的索引是:{1}".format(word, word_to_index[word]))
print("索引{0}对应的单词是:{1}".format(index, index_to_word[index]))
单词cucumber对应的索引是:113317
索引113317对应的单词是:cucumber

我们将实现sentence_to_avg()函数,我们可以将之分为以下两个步骤:

  1. 把每个句子转换为小写,然后分割为列表。我们可以使用X.lower() 与 X.split()
  2. 对于句子中的每一个单词,转换为GloVe向量,然后对它们取平均
def sentence_to_avg(sentence, word_to_vec_map):"""将句子转换为单词列表,提取其GloVe向量,然后将其平均。参数:sentence -- 字符串类型,从X中获取的样本。word_to_vec_map -- 字典类型,单词映射到50维的向量的字典返回:avg -- 对句子的均值编码,维度为(50,)"""# 第一步:分割句子,转换为列表。words = sentence.lower().split()# 初始化均值词向量avg = np.zeros(50,)# 第二步:对词向量取平均。for w in words:avg += word_to_vec_map[w]avg = np.divide(avg, len(words))return avg
avg = sentence_to_avg("Morrocan couscous is my favorite dish", word_to_vec_map)
print("avg = ", avg)
avg =  [-0.008005    0.56370833 -0.50427333  0.258865    0.55131103  0.03104983-0.21013718  0.16893933 -0.09590267  0.141784   -0.15708967  0.185258670.6495785   0.38371117  0.21102167  0.11301667  0.02613967  0.260377670.05820667 -0.01578167 -0.12078833 -0.02471267  0.4128455   0.51520610.38756167 -0.898661   -0.535145    0.33501167  0.68806933 -0.21562651.797155    0.10476933 -0.36775333  0.750785    0.10282583  0.348925-0.27262833  0.66768    -0.10706167 -0.283635    0.59580117  0.28747333-0.3366635   0.23393817  0.34349183  0.178405    0.1166155  -0.0764330.1445417   0.09808667]

我们现在应该实现所有的模型结构了,在使用sentence_to_avg()之后,进行前向传播,计算损失,再进行反向传播,最后再更新参数

我们根据图2-2实现model()函数,Y o n YonYon是已经经过独热编码后的Y YY,那么前向传播以及计算损失的公式如下:

当然你可能有更高效率的向量化实现方式,但是这里我们只使用for循环

def model(X, Y, word_to_vec_map, learning_rate=0.01, num_iterations=400):"""在numpy中训练词向量模型。参数:X -- 输入的字符串类型的数据,维度为(m, 1)。Y -- 对应的标签,0-7的数组,维度为(m, 1)。word_to_vec_map -- 字典类型的单词到50维词向量的映射。learning_rate -- 学习率.num_iterations -- 迭代次数。返回:pred -- 预测的向量,维度为(m, 1)。W -- 权重参数,维度为(n_y, n_h)。b -- 偏置参数,维度为(n_y,)"""np.random.seed(1)# 定义训练数量m = Y.shape[0]n_y = 5n_h = 50# 使用Xavier初始化参数W = np.random.randn(n_y, n_h) / np.sqrt(n_h)b = np.zeros((n_y,))# 将Y转换成独热编码Y_oh = emo_utils.convert_to_one_hot(Y, C=n_y)# 优化循环for t in range(num_iterations):for i in range(m):# 获取第i个训练样本的均值avg = sentence_to_avg(X[i], word_to_vec_map)# 前向传播z = np.dot(W, avg) + ba = emo_utils.softmax(z)# 计算第i个训练的损失cost = -np.sum(Y_oh[i]*np.log(a))# 计算梯度dz = a - Y_oh[i]dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h))db = dz# 更新参数W = W - learning_rate * dWb = b - learning_rate * dbif t % 100 == 0:print("第{t}轮,损失为{cost}".format(t=t,cost=cost))pred = emo_utils.predict(X, Y, W, b, word_to_vec_map)return pred, W, b
print(X_train.shape)
print(Y_train.shape)
print(np.eye(5)[Y_train.reshape(-1)].shape)
print(X_train[0])
print(type(X_train))
Y = np.asarray([5,0,0,5, 4, 4, 4, 6, 6, 4, 1, 1, 5, 6, 6, 3, 6, 3, 4, 4])
print(Y.shape)X = np.asarray(['I am going to the bar tonight', 'I love you', 'miss you my dear','Lets go party and drinks','Congrats on the new job','Congratulations','I am so happy for you', 'Why are you feeling bad', 'What is wrong with you','You totally deserve this prize', 'Let us go play football','Are you down for football this afternoon', 'Work hard play harder','It is suprising how people can be dumb sometimes','I am very disappointed','It is the best day in my life','I think I will end up alone','My life is so boring','Good job','Great so awesome'])
(132,)
(132,)
(132, 5)
never talk to me again
<class 'numpy.ndarray'>
(20,)
pred, W, b = model(X_train, Y_train, word_to_vec_map)
第0轮,损失为1.9520498812810072
Accuracy: 0.3484848484848485
第100轮,损失为0.07971818726014807
Accuracy: 0.9318181818181818
第200轮,损失为0.04456369243681402
Accuracy: 0.9545454545454546
第300轮,损失为0.03432267378786059
Accuracy: 0.9696969696969697

2.1.4 - 验证集

print("=====训练集====")
pred_train = emo_utils.predict(X_train, Y_train, W, b, word_to_vec_map)
print("=====测试集====")
pred_test = emo_utils.predict(X_test, Y_test, W, b, word_to_vec_map)
=====训练集====
Accuracy: 0.9772727272727273
=====测试集====
Accuracy: 0.8571428571428571

假设有5个类别,随机猜测的准确率在20%左右,但是仅仅经过127个样本的训练,就有很好的表现。在训练集中,算法看到了“I love you”的句子,其标签为“❤️”,在训练集中没有“adore”这个词汇,如果我们写“I adore you”会发生什么?

X_my_sentences = np.array(["i adore you", "i love you", "funny lol", "lets play with a ball", "food is ready", "you are not happy"])
Y_my_labels = np.array([[0], [0], [2], [1], [4],[3]])pred = emo_utils.predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map)
emo_utils.print_predictions(X_my_sentences, pred)
Accuracy: 0.8333333333333334i adore you ❤️
i love you ❤️
funny lol :smile:
lets play with a ball ⚾
food is ready 												

序列模型 - 词向量的运算与Emoji生成器相关推荐

  1. 【中文】【吴恩达课后编程作业】Course 5 - 序列模型 - 第二周作业 - 词向量的运算与Emoji生成器

    [中文][吴恩达课后编程作业]Course 5 - 序列模型 - 第二周作业 - 词向量的运算与Emoji生成器 上一篇:[课程5 - 第二周测验]※※※※※ [回到目录]※※※※※下一篇:[课程5 ...

  2. 序列模型第二周作业1:Operations on word vectors

    来自吴恩达深度学习系列视频:序列模型第二周作业1:Operations on word vectors.如果英文对你来说有困难,可以参照:[中文][吴恩达课后编程作业]Course 5 - 序列模型 ...

  3. 词袋模型(BOW,bag of words)和词向量模型(Word Embedding)理解

    Word2vec 向量空间模型在信息检索中是众所周知的,其中每个文档被表示为向量.矢量分量表示文档中每个单词的权重或重要性.使用余弦相似性度量计算两个文档之间的相似性. 尽管对单词使用矢量表示的想法也 ...

  4. 使用Google word2vec训练我们自己的词向量模型

    主要内容 这篇文章主要内容是介绍从初始语料(文本)到生成词向量模型的过程. 词向量模型 词向量模型是一种表征词在整个文档中定位的模型.它的基本内容是词以及它们的向量表示,即将词映射为对应的向量,这样就 ...

  5. 利用gensim构建word2vec词向量模型并保存词向量

    利用gensim包的word2vec模块构建CBOW或Skip-Gram模型来进行词向量化比较方便. 具体gensim.models.Word2Vec模型的参数可以看官网介绍: https://rad ...

  6. 【NLP】⚠️学不会打我! 半小时学会基本操作 2⚠️词向量模型简介

    [NLP]⚠️学不会打我! 半小时学会基本操作 2⚠️词向量模型简介 概述 词向量维度 Word2Vec CBOW 模型 Skip-Gram 模型 负采样模型 词向量的训练过程 1. 初始化词向量矩阵 ...

  7. 【NLP】⚠️学不会打我! 半小时学会基本操作 4⚠️词向量模型

    [NLP]⚠️学不会打我! 半小时学会基本操作 4⚠️词向量模型 概述 词向量 词向量维度 Word2Vec CBOW 模型 Skip-Gram 模型 负采样模型 词向量的训练过程 1. 初始化词向量 ...

  8. GENSIM官方教程(4.0.0beta最新版)-Word2Vec词向量模型

    GENSIM官方教程(4.0.0beta最新版)-词向量模型 译文目录 回顾:词袋模型 简介:词向量模型 词向量模型训练实例 训练一个你自己的模型 储存和加载模型 训练参数 内存相关的细节 模型评估 ...

  9. NLP:词袋模型(bag of words)、词向量模型(Word Embedding)

    例句: Jane wants to go to Shenzhen. Bob  wants to go to Shanghai 一.词袋模型     将所有词语装进一个袋子里,不考虑其词法和语序的问题, ...

最新文章

  1. Jmeter 压力测试中关于 Http 的那些事儿
  2. Stanford UFLDL教程 深度网络概览
  3. linux swftools java_linux下安装swftools工具
  4. python代码求和_python求和代码
  5. python 爬取公众号文章_python批量爬取公众号文章
  6. 免费的音视频格式转换网站-ncm, qmc, mflac, mgg转mp3
  7. 分解gif动图如何操作?手把手教你动图分解方法
  8. 深圳计师需要全国计算机证吗,深圳入户需要什么技师证
  9. 视频动作识别调研(Action Recognition)
  10. 计算机专业的梦想作文,我的梦想作文300字(通用15篇)
  11. 把数组改为用逗号隔开的形式
  12. [ARC084]E - Finite Encyclopedia of Integer Sequences 乱搞
  13. ffmpeg + cuda(cuvid) 硬解码+像素格式转换(cpu主导)实战
  14. LearnGL - 11.1 - 实现简单的Gouraud光照模型 dot 点积/点乘的作用
  15. m.soudashi.cn 地图_网站百度排名推广的基本操作是什么
  16. 设置页面图标和动态title
  17. iOS 测试利器:idb
  18. 基于Cython编译整个Python项目并保留原项目结构
  19. 小刀娱乐网:引流的四个思维分析,如何更好发展网站!
  20. 磁盘扩展和缩减知识汇总

热门文章

  1. 学习python用哪个app-python做app用什么工具
  2. 整理了下这三天【面试】遇到的让人心惊胆颤的难题。
  3. Activiti应用
  4. 冈萨雷斯《数字图像处理》学习笔记(4)--图像复原与重建(含傅里叶切片定理推导)
  5. 《Non-contact Eye Gaze Tracking System by Mapping of Corneal Reflections》论文阅读
  6. flex布局(flex容器,flex属性)
  7. python计算圆周率的方法_用python计算圆周率PI
  8. 鸿蒙dnf怎么样,DNF:最保值时装终于再出,当年卖300如今值5000,又是全服真香?...
  9. VBA 收集 Word关键字批量处理
  10. 24个提高你的知识和技能极限的数据科学(机器学习)项目(免费)