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

2023-10-27

Part 2: Emojify

欢迎来到本周的第二个作业,你将利用词向量构建一个表情包。

你有没有想过让你的短信更具表现力? emojifier APP将帮助你做到这一点。 所以不是写下”Congratulations on the promotion! Lets get coffee and talk. Love you!” emojifier可以自动转换为 “Congratulations on the promotion! ? Lets get coffee and talk. ☕️ Love you! ❤️”

另外,如果你对emojis不感兴趣,但有朋友向你发送了使用太多表情符号的疯狂短信,你还可以使用emojifier来回复他们。

你将实现一个模型,输入一个句子(“Let’s go see the baseball game tonight!”),并找到最适合这个句子的表情符号(⚾️)。 在许多表情符号界面中,您需要记住❤️是”heart”符号而不是”love”符号。 但是使用单词向量,你会发现即使你的训练集只将几个单词明确地与特定的表情符号相关联,你的算法也能够将测试集中相关的单词概括并关联到相同的表情符号上,即使这些词没有出现在训练集中。这使得即使使用小型训练集,你也可以建立从句子到表情符号的精确分类器映射。

在本练习中,您将从使用词嵌入的基本模型(Emojifier-V1)开始,然后构建进一步整合LSTM的更复杂的模型(Emojifier-V2)。

导包

import numpy as np
from emo_utils import *
import emoji
import matplotlib.pyplot as plt

%matplotlib inline

emo_utils 中有用的函数

import csv
import numpy as np
import emoji
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

def read_glove_vecs(glove_file):
    with open(glove_file, 'r') 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)

        i = 1
        words_to_index = {}
        index_to_words = {}
        for w in sorted(words):
            words_to_index[w] = i
            index_to_words[i] = w
            i = i + 1
    return words_to_index, index_to_words, word_to_vec_map

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()


def read_csv(filename = 'data/emojify_data.csv'):
    phrase = []
    emoji = []

    with open (filename) as csvDataFile:
        csvReader = csv.reader(csvDataFile)

        for row in csvReader:
            phrase.append(row[0])
            emoji.append(row[1])

    X = np.asarray(phrase)
    Y = np.asarray(emoji, dtype=int)

    return X, Y

def convert_to_one_hot(Y, C):
    Y = np.eye(C)[Y.reshape(-1)]
    return Y


emoji_dictionary = {
  "0": "\u2764\uFE0F",    # :heart: prints a black instead of red heart depending on the font
                    "1": ":baseball:",
                    "2": ":smile:",
                    "3": ":disappointed:",
                    "4": ":fork_and_knife:"}

def label_to_emoji(label):
    """
    Converts a label (int or string) into the corresponding emoji code (string) ready to be printed
    """
    return emoji.emojize(emoji_dictionary[str(label)], use_aliases=True)


def print_predictions(X, pred):
    print()
    for i in range(X.shape[0]):
        print(X[i], label_to_emoji(int(pred[i])))


def plot_confusion_matrix(y_actu, y_pred, title='Confusion matrix', cmap=plt.cm.gray_r):

    df_confusion = pd.crosstab(y_actu, y_pred.reshape(y_pred.shape[0],), rownames=['Actual'], colnames=['Predicted'], margins=True)

    df_conf_norm = df_confusion / df_confusion.sum(axis=1)

    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)


def predict(X, Y, W, b, word_to_vec_map):
    """
    Given X (sentences) and Y (emoji indices), predict emojis and compute the accuracy of your model over the given set.

    Arguments:
    X -- input data containing sentences, numpy array of shape (m, None)
    Y -- labels, containing index of the label emoji, numpy array of shape (m, 1)

    Returns:
    pred -- numpy array of shape (m, 1) with your predictions
    """
    m = X.shape[0]
    pred = np.zeros((m, 1))

    for j in range(m):                       # Loop over training examples

        # Split jth test example (sentence) into list of lower case words
        words = X[j].lower().split()

        # Average words' vectors
        avg = np.zeros((50,))
        for w in words:
            avg += word_to_vec_map[w]
        avg = avg/len(words)

        # Forward propagation
        Z = np.dot(W, avg) + b
        A = softmax(Z)
        pred[j] = np.argmax(A)

    print("Accuracy: "  + str(np.mean((pred[:] == Y.reshape(Y.shape[0],1)[:]))))

    return pred

1 基本模型:Emojifier-V1

1.1 emoji 数据集

我们先来建立一个简单的分类器。

我们有一个小型数据集(X, Y):

  • X 包含127个句子
  • Y 包含标号为0-4的对应于每个句子的表情

image

下面导入数据集,训练集127个例子,测试集56个例子

X_train, Y_train = read_csv('data/train_emoji.csv')
X_test, Y_test = read_csv('data/tesss.csv')

maxLen = len(max(X_train, key=len).split())

查看训练集数据

index = 1
print(X_train[index], label_to_emoji(Y_train[index]))

1.2 Emojifier-V1 概述

在这一部分,我们要实现一个名为”Emojifier-v1” 的模型
image

模型的输入是一个句子,输出是(1,5)的概率向量,然后通过argmax层得出最适合的预测表情。

为了将我们的标签转换为适合训练softmax分类器的格式,我们将Y从(m,1)转换为”one-hot” 的(m,5)。如下转换中 Y_oh 表示”Y-one-hot”。

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

index = 50
print(Y_train[index], "is converted into one hot", Y_oh_train[index])

# 0 is converted into one hot [ 1.  0.  0.  0.  0.]

数据准备就绪,下面可以实现模型了。

1.3 实现 Emojifier-V1

首先需要将输入的句子转换为词向量再求平均值,我们仍然使用50维的 Glove 词嵌入。
导入word_to_vec_map,其中包含了所有的向量表示。

word_to_index, index_to_word, word_to_vec_map = 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 = 289846
print("the index of", word, "in the vocabulary is", word_to_index[word])
print("the", str(index) + "th word in the vocabulary is", index_to_word[index])

# the index of cucumber in the vocabulary is 113317
# the 289846th word in the vocabulary is potatos
练习:实现 sentence_to_avg()
  1. 将每个句子转换为小写,然后拆分句子为单词列表(可以使用X.lower() 和 X.split())
  2. 取出句子中每个单词的 Glove 向量,然后求平均值
# GRADED FUNCTION: sentence_to_avg

def sentence_to_avg(sentence, word_to_vec_map):
    """
    Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word
    and averages its value into a single vector encoding the meaning of the sentence.

    Arguments:
    sentence -- string, one training example from X
    word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation

    Returns:
    avg -- average vector encoding information about the sentence, numpy-array of shape (50,)
    """

    ### START CODE HERE ###
    # Step 1: Split sentence into list of lower case words (鈮?1 line)
    words = sentence.lower().split()

    # Initialize the average word vector, should have the same shape as your word vectors.
    avg = np.zeros((50,))

    # Step 2: average the word vectors. You can loop over the words in the list "words".
    for w in words:
        avg += word_to_vec_map[w]
    avg = avg/len(words)

    ### END CODE HERE ###

    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.18525867
#   0.6495785   0.38371117  0.21102167  0.11301667  0.02613967  0.26037767
#   0.05820667 -0.01578167 -0.12078833 -0.02471267  0.4128455   0.5152061
#   0.38756167 -0.898661   -0.535145    0.33501167  0.68806933 -0.2156265
#   1.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.076433
#   0.1445417   0.09808667]

期待的输出

key value
avg [-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.26037767 0.05820667 -0.01578167 -0.12078833 -0.02471267 0.4128455 0.5152061 0.38756167 -0.898661 -0.535145 0.33501167 0.68806933 -0.2156265 1.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.076433 0.1445417 0.09808667]

模型

你已经实现了 model 的各个部分。在sentence_to_avg()之后需要将平均值进行前向传播、计算损失、后向传播以及更新参数。

练习:实现 model()

假设这里的 Yoh(“Y one hot”)为输出标签的”one-hot”表示,下面公式用于前向传播和计算交叉熵。

z
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • SpringBoot日志配置【详解】

    文章目录 前言 1 为什么使用Logback 2 Logback使用 2 1 添加依赖 2 2 默认配置 3 logback spring xml详解 3 1 configuration元素 3 2 logger 元素 3 3 root 元
  • 购物商城---页面缓存oscached

    流程图 web xml
  • VC++使用HOOK API 屏蔽PrintScreen键截屏以及QQ和微信默认热键截屏

    转载 http blog csdn net easysec article details 8833457 转载 http www vckbase com module articleContent php id 567 title 用VS
  • 离线安装Docker镜像

    部分线上服务器无法连接公网 或者服务器下载镜像比较慢 遇到这种情况要怎么解决 我们可以在联网的本机或服务器上 将已经下载好的镜像导出 然后导入到没有网络的服务器上 通过Docker加载 例如 这里有一个镜像grafana loki 2 2
  • 订单系统开发

    一 订单系统基本框架的搭建 1 创建maven工程 pom xml文件内容如下
  • WSA with Magisk Root安装配置教程(2023.5)

    前言 最近正式走上了安卓逆向的道路 刚开始尝试了各种模拟器 雷电 夜神 及其海外版 并且安装配置了多次magisk 倒不是说这些模拟器的体验有多差 主要还是不能与 Windows Hype V 共存导致无法使用 WSL 这点让我无法接受 s
  • markdown语法最全汇总

    一 markdown简介 注 如果对markdown有一定了解 可以略过此处 第一章主要对markdown基础知识做个补充 摘自菜鸟教程此处原文档 博客原地址 欢迎收藏访问 1 1 markdown背景 1 markdown是一种轻量级标记

随机推荐

  • 一枚芯片的实际成本是多少?(1)

    芯片的硬件成本构成 芯片的成本包括芯片的硬件成本和芯片的设计成本 芯片硬件成本包括晶片成本 掩膜成本 测试成本 封装成本四部分 像ARM阵营的IC设计公司要支付给ARM设计研发费以及每一片芯片的版税 但笔者这里主要描述自主CPU和Intel
  • shiny教程一 -- shiny入门

    Shiny是一个R软件包 可轻松从R直接构建交互式Web应用程序 本课程将使您立即开始构建Shiny应用程序 如果还未安装Shiny软件包 打开R会话窗 确保联网状态 然后运行 install packages shiny Shiny软件包
  • vue 中click.stop的用法

    click stop 阻止点击事件继续传播 场景 在table中使用 点击当前行 当前行被勾选 但是点击当前行中按钮或点击事件时 使用此方法 则在触发当前点击事件后 阻止行的选中事件 使用 html
  • input“输入框”常见问题及解决方法

    1 ios中 输入框获得焦点时 页面输入框被遮盖 定位的元素位置错乱 当页input存在于吸顶或者吸底元素中时 用户点击输入框 输入法弹出后 fiexd失效 页面中定位好的元素随屏幕滚动 针对这个问题 我们一起来看下以下几种方案 方案一 W
  • FOXBORO FBM232 P0926GW 自动化控制模块

    Foxboro FBM232 P0926GW 是 Foxboro 福克斯博罗 自动化控制系统的一部分 通常用于监测和控制工业过程 以下是关于这种类型的自动化控制模块可能具有的一些常见功能 数字输入通道 FBM232 P0926GW 控制模块
  • 鸿蒙系统 服务器,鸿蒙开发之环境准备【1】-基于Deepin20操作系统的编译服务器环境搭建遇到的问题及解决方式...

    Hi3861 code 1 0 python build py wifiiot 196 197 ACTION vendor hisi hi3861 hi3861 run wifiiot scons build lite toolchain
  • vscode launch.json 常用配置

    Use IntelliSense to learn about possible attributes Hover to view descriptions of existing attributes For more informati
  • 毕业设计-基于机器视觉的智能安检系统设计 -OpenCV

    目录 前言 课题背景和意义 实现技术思路 一 智能安检机概述 二 嵌入式控制系统 三 图像处理模块设计 实现效果图样例 最后 前言 大四是整个大学期间最忙碌的时光 一边要忙着备考或实习为毕业后面临的就业升学做准备 一边要为毕业设计耗费大量精
  • Blender石头雕刻

    1 建立一个plane 选中一个点后ctrl I反选其他的点 然后删去 2 e挤出点 3 添加蒙皮skin修改器 4 全选所有点 ctrl a放大或缩小
  • Caffeine缓存不刷新问题

    一 先看问题代码 缓存管理器配置 import java util concurrent TimeUnit import org springframework cache CacheManager import org springfra
  • springboot同一个类里的方法之间调用事务不起作用

    今天在看项目代码的时候 发现在service层 有方法调用同类中的方法 SonarLint提示有bug 下图是我自己做测试时写的demo代码 经过测试发现 当A方法调用同类中带有 Transactional注解的B方法时 被 Transac
  • JVM学习笔记3:内存溢出的十个场景

    内存溢出的十个场景 JVM运行时首先需要类加载器 classLoader 加载所需类的字节码文件 加载完毕交由执行引擎执行 在执行过程中需要一段空间来存储数据 类比CPU与主存 这段内存空间的分配和释放过程正是我们需要关心的运行时数据区 内
  • 常见计算机英语,常见计算机英语词汇

    电脑 又称计算机 是机械的一种 现在使用的越来越多 接下来小编为大家整理了常见计算机英语词汇 希望对你有帮助哦 adder加法器 address地址 access arm磁头臂 存取臂 access time存取时间 alphanumeri
  • Java中的静态成员方法

    用static修饰的变量 方法叫静态成员 方法 属于整个类所有 而不是某个对象所有 即被类的所有对象所共享 静态成员可以使用类名直接访问 也可以使用对象名进行访问 Java中静态方法与非静态方法的区别 首先 两者本质上的区别是 静态方法是在
  • 2021-06-01 通过类去实现装饰器__call__.

    1 含有 init 的类 class MyClass a cherry def init self age sex self age age self sex sex def say self print hello obj MyClass
  • Quartz的MisFire机制解析

    在上一篇 Quartz的负载均衡如何实现 文章中说过Quartz的线程模型 提到了MisFire任务是由MisfireHandler线程专门进行处理的 本文主要是来了解下该部分功能是如何实现的 源码分析 MisfireHandler线程定义
  • java 上传方法_Java实现文件上传的方法

    本文实例为大家分享了java实现文件上传的具体代码 具体内容如下 1 java代码 package com github reston servlet import java io file import java io fileoutpu
  • 添加高斯噪声

    coding utf 8 import cv2 as cv import numpy as np import sys def add noise image mean 0 val 0 01 size image shape image i
  • 用本机电脑搭建网站(域名、DNS解析)

    最近又准备瞎捣鼓一下个人网站 本来呢 如果是自己玩玩的话 用花生壳或者NAT123这样的动态DNS解析就可以了 但是最近花生壳这个吊玩意不知道怎么又没办法解析了 而且这货给的域名用的是我的手机号 如此一来个人隐私也暴露了 所以今天我就来研究
  • 吴恩达Coursera深度学习课程 deeplearning.ai (5-2) 自然语言处理与词嵌入--编程作业(二):Emojify表情包

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