C2W2.Assignment.Parts-of-Speech Tagging (POS).Part2

理论课:C2W2.Part-of-Speech (POS) Tagging and Hidden Markov Models

文章目录

  • 2 Hidden Markov Models
    • 2.1 Generating Matrices
      • Creating the `A` transition probabilities matrix
      • Exercise 03
      • Create the `B` emission probabilities matrix
      • Exercise 04

理论课: C2W2.Part-of-Speech (POS) Tagging and Hidden Markov Models

2 Hidden Markov Models

本节将使用维特比算法实现HMM:

  • HMM 是自然语言处理中最常用的算法之一,也是该领域中许多深度学习技术的基础。
  • 除了POS,HMM 还用于语音识别、语音合成等。
  • 完成这部分作业,可在Part 1 使用的相同数据集上获得 95% 的准确率。

马尔可夫模型中包含若干状态以及这些状态之间的转换概率。

  • 在本例中,状态就是词性标签。
  • 马尔可夫模型中状态的转换可以使用一个转换矩阵 A表示。
  • 隐马尔可夫模型增加了一个观测或发射矩阵B,它描述了当我们处于特定状态时可见观测的概率。观测发射矩阵就是语料库中的单词。
  • 被隐藏的状态是该单词的词性标签。

2.1 Generating Matrices

Creating the A transition probabilities matrix

在Part 1中已经计算了emission_counts, transition_counts, tag_counts,使用这三个矩阵可以很容易的构造出A和B

ARBSRPSYMTOUH
RBS2.217069e-062.217069e-062.217069e-060.0088702.217069e-06
RP3.756509e-077.516775e-043.756509e-070.0510893.756509e-07
SYM1.722772e-051.722772e-051.722772e-050.0000171.722772e-05
TO4.477336e-054.472863e-084.472863e-080.0000904.477336e-05
UH1.030439e-051.030439e-051.030439e-050.0618373.092348e-02

注意:以上的计算结果示例是经过平滑后的。每个单元格都给出了从一个词性标签到另一个词性标签的概率。

  • 如:从词性标签 TORP 的概率为 4.47e-8。
  • 每一行的总和必须等于 1,因为模型假设下一个 POS 标记必须是表中可用列之一。

平滑处理的方法如下:
P ( t i ∣ t i − 1 ) = C ( t i − 1 , t i ) + α C ( t i − 1 ) + α ∗ N (3) P(t_i | t_{i-1}) = \frac{C(t_{i-1}, t_{i}) + \alpha }{C(t_{i-1}) +\alpha * N}\tag{3} P(titi1)=C(ti1)+αNC(ti1,ti)+α(3)

  • N N N 是标签总数
  • C ( t i − 1 , t i ) C(t_{i-1}, t_{i}) C(ti1,ti)是 “transition_counts ”字典中元组(前一个 POS、当前 POS)的计数。
  • C ( t i − 1 ) C(t_{i-1}) C(ti1)是 “tag_counts ”字典中前一个 POS 的计数。
  • α \alpha α 是一个平滑参数。

Exercise 03

根据公式3实现函数create_transition_matrix
函数主要目的是创建一个转移矩阵 A,这个矩阵通常用于隐马尔可夫模型(HMM)中,表示状态(在这里是词性标签)之间转移的概率。以下是代码的详细解释:

输入参数:

  • alpha:平滑参数,用于在计算概率时避免零概率问题,提高模型的鲁棒性。
  • tag_counts:一个字典,映射每个词性标签到它的出现次数。
  • transition_counts:一个字典,其键是前一个词性标签和当前词性标签的元组,值是这些转换发生的次数。

输出:

  • A:一个维度为 (num_tags, num_tags) 的转移矩阵。

函数逻辑:

  1. 获取所有唯一的词性标签,并对它们进行排序,存储在 all_tags 列表中。
  2. 计算词性标签的种类数量,存储在变量 num_tags 中。
  3. 初始化转移矩阵 A,其大小为 (num_tags, num_tags),初始值为零。
  4. 获取所有唯一的转换元组,这些元组是 transition_counts 字典的键,存储在 trans_keys 集合中。
  5. 遍历转移矩阵 A 的每一行(代表前一个状态的词性标签):
    • 对于矩阵 A 的每一列(代表当前状态的词性标签):
      • 初始化当前转换的计数 count 为零。
      • 定义一个转换元组 key,它包含前一个词性标签和当前词性标签。
      • 检查 key 是否存在于 transition_counts 字典中:
        • 如果存在,从字典中获取对应的计数 count。
      • 从 tag_counts 字典中获取前一个词性标签的计数 count_prev_tag。
      • 应用平滑技术,使用公式3来计算转移概率,并将其赋值给矩阵 A 的对应位置。
  6. 返回填充好的转移矩阵 A。
# UNQ_C3 GRADED FUNCTION: create_transition_matrix
def create_transition_matrix(alpha, tag_counts, transition_counts):''' Input: alpha: number used for smoothingtag_counts: a dictionary mapping each tag to its respective counttransition_counts: a dictionary where the keys are (prev_tag, tag) and the values are the countsOutput:A: matrix of dimension (num_tags,num_tags)'''# Get a sorted list of unique POS tagsall_tags = sorted(tag_counts.keys())# Count the number of unique POS tagsnum_tags = len(all_tags)# Initialize the transition matrix 'A'A = np.zeros((num_tags,num_tags))# Get the unique transition tuples (previous POS, current POS)trans_keys = set(transition_counts.keys())### START CODE HERE ### # Go through each row of the transition matrix Afor i in range(num_tags):# Go through each column of the transition matrix Afor j in range(num_tags):# Initialize the count of the (prev POS, current POS) to zerocount = 0# Define the tuple (prev POS, current POS)# Get the tag at position i and tag at position j (from the all_tags list)key = (all_tags[i],all_tags[j]) # tuple of form (tag,tag)# Check if the (prev POS, current POS) tuple # exists in the transition counts dictionaryif transition_counts: # Replace None in this line with the proper condition.# Get count from the transition_counts dictionary # for the (prev POS, current POS) tuplecount = transition_counts[key]               # Get the count of the previous tag (index position i) from tag_countscount_prev_tag = tag_counts[all_tags[i]]# Apply smoothing using count of the tuple, alpha, # count of previous tag, alpha, and total number of tagsA[i,j] = (count + alpha) / (count_prev_tag + alpha*num_tags)### END CODE HERE ###return A

测试:

alpha = 0.001
A = create_transition_matrix(alpha, tag_counts, transition_counts)
# Testing your function
print(f"A at row 0, col 0: {A[0,0]:.9f}")
print(f"A at row 3, col 1: {A[3,1]:.4f}")print("View a subset of transition matrix A")
A_sub = pd.DataFrame(A[30:35,30:35], index=states[30:35], columns = states[30:35] )
print(A_sub)

结果:

A at row 0, col 0: 0.000007040
A at row 3, col 1: 0.1691
View a subset of transition matrix ARBS            RP           SYM        TO            UH
RBS  2.217069e-06  2.217069e-06  2.217069e-06  0.008870  2.217069e-06
RP   3.756509e-07  7.516775e-04  3.756509e-07  0.051089  3.756509e-07
SYM  1.722772e-05  1.722772e-05  1.722772e-05  0.000017  1.722772e-05
TO   4.477336e-05  4.472863e-08  4.472863e-08  0.000090  4.477336e-05
UH   1.030439e-05  1.030439e-05  1.030439e-05  0.061837  3.092348e-02

Create the B emission probabilities matrix

B矩阵对应的公式为:
P ( w i ∣ t i ) = C ( t i , w o r d i ) + α C ( t i ) + α ∗ N (4) P(w_i | t_i) = \frac{C(t_i, word_i)+ \alpha}{C(t_{i}) +\alpha * N}\tag{4} P(witi)=C(ti)+αNC(ti,wordi)+α(4)

  • C ( t i , w o r d i ) C(t_i,word_i) C(ti,wordi)是训练数据中 t a g i tag_i tagi调节下 w o r d i word_i wordi观测到的次数(存储在emission_counts字典中)。
  • C ( t i ) C(t_i) C(ti) t a g i tag_i tagi在训练数据中出现的总次数(存储在tag_counts字典中)。
  • N N N 是词汇表中的单词数
  • α \alpha α 是一个平滑参数。

B矩阵维度为(num_tags, N),下面是一个示例

B725adroitlyengineerspromotedsynergy
CD8.201296e-052.732854e-082.732854e-082.732854e-082.732854e-08
NN7.521128e-097.521128e-097.521128e-097.521128e-092.257091e-05
NNS1.670013e-081.670013e-084.676203e-041.670013e-081.670013e-08
VB3.779036e-083.779036e-083.779036e-083.779036e-083.779036e-08
RB3.226454e-086.456135e-053.226454e-083.226454e-083.226454e-08
RP3.723317e-073.723317e-073.723317e-073.723317e-073.723317e-07

Exercise 04

完成create_emission_matrix函数,其主要目的是创建一个发射矩阵 B,这个矩阵通常用于隐马尔可夫模型(HMM)中,表示在给定状态(在这里是词性标签)下观测到某个观测值(在这里是单词)的概率。以下是代码的详细解释:

输入参数:

  • alpha:平滑参数,用于在计算概率时避免零概率问题,提高模型的鲁棒性。
  • tag_counts:一个字典,映射每个词性标签到它的出现次数。
  • emission_counts:一个字典,其键是词性标签和单词的元组,值是这些发射发生的次数。
  • vocab:一个字典,其键是词汇表中的单词,值是索引。在这个函数中,vocab 被当作列表处理。

输出:

  • B:一个维度为 (num_tags, len(vocab)) 的发射矩阵。

函数逻辑:

  1. 获取词性标签的数量,存储在变量 num_tags 中。
  2. 获取所有唯一的词性标签,并对它们进行排序,存储在 all_tags 列表中。
  3. 获取词汇表中单词的总数,存储在变量 num_words 中。
  4. 初始化发射矩阵 B,其大小为 (num_tags, num_words),初始值为零。
  5. 获取所有唯一的 (词性标签, 单词) 元组,这些元组是 emission_counts 字典的键,存储在 emis_keys 集合中。
  6. 遍历发射矩阵 B 的每一行(代表词性标签):
    • 对于矩阵 B 的每一列(代表词汇表中的单词):
      • 初始化当前发射的计数 count 为零。
      • 定义一个 (词性标签, 单词) 元组 key。
      • 检查 key 是否存在于 emission_counts 字典中:
        • 如果存在,从字典中获取对应的计数 count。
      • 从 tag_counts 字典中获取当前词性标签的计数 count_tag。
      • 应用平滑技术,使用公式4来计算观测概率,并将其赋值给矩阵 B 的对应位置。
  7. 返回填充好的观测概率矩阵 B。
# UNQ_C4 GRADED FUNCTION: create_emission_matrixdef create_emission_matrix(alpha, tag_counts, emission_counts, vocab):'''Input: alpha: tuning parameter used in smoothing tag_counts: a dictionary mapping each tag to its respective countemission_counts: a dictionary where the keys are (tag, word) and the values are the countsvocab: a dictionary where keys are words in vocabulary and value is an index.within the function it'll be treated as a listOutput:B: a matrix of dimension (num_tags, len(vocab))'''# get the number of POS tagnum_tags = len(tag_counts)# Get a list of all POS tagsall_tags = sorted(tag_counts.keys())# Get the total number of unique words in the vocabularynum_words = len(vocab)# Initialize the emission matrix B with places for# tags in the rows and words in the columnsB = np.zeros((num_tags, num_words))# Get a set of all (POS, word) tuples # from the keys of the emission_counts dictionaryemis_keys = set(list(emission_counts.keys()))### START CODE HERE (Replace instances of 'None' with your code) #### Go through each row (POS tags)for i in range(num_tags): # complete this line# Go through each column (words)for j in range(num_words): # complete this line# Initialize the emission count for the (POS tag, word) to zerocount = 0# Define the (POS tag, word) tuple for this row and columnkey =  (all_tags[i],vocab[j])# check if the (POS tag, word) tuple exists as a key in emission countsif key in emission_counts.keys(): # complete this line# Get the count of (POS tag, word) from the emission_counts dcount = emission_counts[key]# Get the count of the POS tagcount_tag = tag_counts[all_tags[i]]# Apply smoothing and store the smoothed value # into the emission matrix B for this row and columnB[i,j] = (count + alpha) / (count_tag+ alpha*num_words)### END CODE HERE ###return B

测试:

# creating your emission probability matrix. this takes a few minutes to run. 
alpha = 0.001
B = create_emission_matrix(alpha, tag_counts, emission_counts, list(vocab))print(f"View Matrix position at row 0, column 0: {B[0,0]:.9f}")
print(f"View Matrix position at row 3, column 1: {B[3,1]:.9f}")# Try viewing emissions for a few words in a sample dataframe
cidx  = ['725','adroitly','engineers', 'promoted', 'synergy']# Get the integer ID for each word
cols = [vocab[a] for a in cidx]# Choose POS tags to show in a sample dataframe
rvals =['CD','NN','NNS', 'VB','RB','RP']# For each POS tag, get the row number from the 'states' list
rows = [states.index(a) for a in rvals]# Get the emissions for the sample of words, and the sample of POS tags
B_sub = pd.DataFrame(B[np.ix_(rows,cols)], index=rvals, columns = cidx )
print(B_sub)

结果:

View Matrix position at row 0, column 0: 0.000006032
View Matrix position at row 3, column 1: 0.000000720725      adroitly     engineers      promoted       synergy
CD   8.201296e-05  2.732854e-08  2.732854e-08  2.732854e-08  2.732854e-08
NN   7.521128e-09  7.521128e-09  7.521128e-09  7.521128e-09  2.257091e-05
NNS  1.670013e-08  1.670013e-08  4.676203e-04  1.670013e-08  1.670013e-08
VB   3.779036e-08  3.779036e-08  3.779036e-08  3.779036e-08  3.779036e-08
RB   3.226454e-08  6.456135e-05  3.226454e-08  3.226454e-08  3.226454e-08
RP   3.723317e-07  3.723317e-07  3.723317e-07  3.723317e-07  3.723317e-07

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/873929.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

FastAPI 学习之路(五十六)将token缓存到redis

在之前的文章中,FastAPI 学习之路(二十九)使用(哈希)密码和 JWT Bearer 令牌的 OAuth2,FastAPI 学习之路(二十八)使用密码和 Bearer 的简单 OAuth2,FastAPI 学习之路&…

Kubernetes 之 Ingress

Kubernetes 之 Ingress 定义 Ingress 可以把外部需要进入到集群内部的请求转发到集群中的一些服务上,从而实现把服务映射到集群外部的需要。Ingress 能把集群内 Service 配置成外网能够访问的 URL,流量负载均衡,提供基于域名访问的虚拟主机…

RabbitMQ 和 RocketMQ 的区别

RabbitMQ 和 RocketMQ 都是流行的开源消息中间件,它们用于在分布式系统中异步传输消息。尽管它们都实现了核心的消息队列功能,但它们在设计、性能、特性和使用场景上有一些关键的区别: 基础架构: RabbitMQ: 基于AMQP(高级消息队列…

阵列信号处理学习笔记(二)--空域滤波基本原理

阵列信号 阵列信号处理学习笔记(一)–阵列信号处理定义 阵列信号处理学习笔记(二)–空域滤波基本原理 文章目录 阵列信号前言一、阵列信号模型1.1 信号的基本模型1.2 阵列的几何构型1.3 均匀直线阵的阵列信号基本模型 总结 前言…

HOW - React 处理不紧急的更新和渲染

目录 useDeferredValueuseTransitionuseIdleCallback 在 React 中,有一些钩子函数可以帮助你处理不紧急的更新或渲染,从而优化性能和用户体验。 以下是一些常用的相关钩子及其应用场景: useDeferredValue 用途:用于处理高优先级…

嵌入式面试总结

C语言中struct和union的区别 struct和union都是常见的复合结构。 结构体和联合体虽然都是由多个不同的数据类型成员组成的,但不同之处在于联合体中所有成员共用一块地址空间,即联合体只存放了一个被选中的成员,结构体中所有成员占用空间是累…

【网络】windows和linux互通收发

windows和linux互通收发 一、windows的udp客户端代码1、代码剖析2、总体代码 二、linux服务器代码三、成果展示 一、windows的udp客户端代码 1、代码剖析 首先我们需要包含头文件以及lib的一个库&#xff1a; #include <iostream> #include <WinSock2.h> #inclu…

前端页面是如何禁止被查看源码、被下载,被爬取,以及破解方法

文章目录 1.了解禁止查看,爬取原理1.1.JS代码,屏蔽屏蔽键盘和鼠标右键1.2.查看源码时,通过JS控制浏览器窗口变化2.百度文库是如何防止抓包2.1.HTPPS2.2. 动态加载为什么看不到?如何查看动态加载的内容?3.禁止复制,如果解决3.1.禁止复制原理3.2.如何破解1.了解禁止查看,爬…

使用scikit-learn进行机器学习:基础教程

使用scikit-learn进行机器学习&#xff1a;基础教程 Scikit-learn是Python中最流行的机器学习库之一。它提供了简单易用的工具&#xff0c;帮助我们进行数据预处理、模型训练、评估和预测。本文将带你通过一个基础教程&#xff0c;了解如何使用scikit-learn进行机器学习。 1.…

【模板代码】用于编写Threejs Demo的模板代码

基础模板代码 使用须知常规模板代码常规Shader模板代码 使用须知 本模板代码&#xff0c;主要用于编写Threejs的Demo&#xff0c;因为本人在早期学习的过程中&#xff0c;大量抄写Threejs/examples下的代码以及各个demo站的代码&#xff0c;所以养成了编写Threejs的demo的习惯…

SAP 采购订单 Adobe 消息输出

目录 1 简介 2 业务数据例子 3 选择增强 & 代码 1&#xff09;BADI: MM_PUR_S4_PO_MODIFY_HEADER 2&#xff09;BADI: MM_PUR_S4_PO_MODIFY_ITEM 4 自定义 Adobe form 1&#xff09;PO Master form 2&#xff09;PO form 5 前台主数据配置 6 后台配置 1&#xf…

昇思22天

CycleGAN图像风格迁移互换 CycleGAN&#xff08;循环生成对抗网络&#xff09;是一种用于在没有成对训练数据的情况下学习将图像从源域 X 转换到目标域 Y 的方法。该技术的一个重要应用是域迁移&#xff0c;即图像风格迁移。 模型介绍 模型简介: CycleGAN 来自于论文 Unpair…

掌握Rust:函数、闭包与迭代器的综合运用

掌握Rust&#xff1a;函数、闭包与迭代器的综合运用 引言&#xff1a;解锁 Rust 高效编程的钥匙函数定义与模式匹配&#xff1a;构建逻辑的基石高阶函数与闭包&#xff1a;代码复用的艺术迭代器与 for 循环&#xff1a;高效数据处理的引擎综合应用案例&#xff1a;构建一个简易…

Mybatis——一对多处理

环境搭建 与多对一相似&#xff0c;有一些地方需要改动&#xff1a; 实体类&#xff1a; Data public class Student {private int id;private String name;private int tid;} Data public class Teacher {private int id;private String name;// 一个老师拥有多个学生priv…

【LeetCode】day15:110 - 平衡二叉树, 257 - 二叉树的所有路径, 404 - 左叶子之和, 222 - 完全二叉树的节点个数

LeetCode 代码随想录跟练 Day15 110.平衡二叉树257.二叉树的所有路径404.左叶子之和222.完全二叉树的节点个数 110.平衡二叉树 题目描述&#xff1a; 给定一个二叉树&#xff0c;判断它是否是 平衡二叉树 平衡二叉树的定义是&#xff0c;对于树中的每个节点&#xff0c;其左右…

qt自定义控件(QLabel)

先创建自定义控件类painter_label 1.自定义类必须给基类传入父窗口指针 2.重写控件中的方法 3.在UI中创建一个QLabel,右键“提升为”&#xff0c;输入类名

动画革命:Lottie如何改变我们对移动应用交互的认知

在数字世界的浩瀚星空中&#xff0c;每一个像素都跃动着无限创意与想象的火花。当静态的界面遇上动态的魔法&#xff0c;一场视觉盛宴便悄然开启。今天&#xff0c;让我们一同揭开一位幕后英雄的神秘面纱——Lottie&#xff0c;这个在UI/UX设计界掀起波澜的动画利器&#xff0c…

掌握构建自动化:如何在Gradle中使用Init脚本进行构建初始化

掌握构建自动化&#xff1a;如何在Gradle中使用Init脚本进行构建初始化 在现代软件开发中&#xff0c;自动化构建是提高效率和一致性的关键。Gradle&#xff0c;作为一个功能强大的构建工具&#xff0c;提供了丰富的自动化支持。其中&#xff0c;Init脚本是Gradle中用于初始化…

SVN与Git功能差异对比分析

最近在调研学习Git管理和分支模型相关内容&#xff0c;外延到了SVN和Git差异、工作原理等相关细节&#xff0c;学习整理如下。 SVN&#xff08;Subversion&#xff09;与 Git 的最大不同&#xff0c;主要包括以下几个方面&#xff1a; 交流探讨&#xff0c;加入群聊【Java学习…

51.2T 800G 以太网交换机,赋能AI开放生态

IB与以太之争 以太网替代IB趋势明显。据相关报告&#xff1a;2024年TOP500的超算中&#xff0c;采用以太网方案占比48.5%&#xff0c;InfiniBand占比为39.2%&#xff0c;其中排名前6的超算中已有5个使用以太网互联。 开放系统战胜封闭系统仅是时间问题。我们已经看到&#xf…