Pytorch在NLP中的简单应用详解


Posted in Python onJanuary 08, 2020

因为之前在项目中一直使用Tensorflow,最近需要处理NLP问题,对Pytorch框架还比较陌生,所以特地再学习一下pytorch在自然语言处理问题中的简单使用,这里做一个记录。

一、Pytorch基础

首先,第一步是导入pytorch的一系列包

import torch
import torch.autograd as autograd #Autograd为Tensor所有操作提供自动求导方法
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

1)Tensor张量

a) 创建Tensors

#tensor
x = torch.Tensor([[1,2,3],[4,5,6]])
#size为2x3x4的随机数随机数
x = torch.randn((2,3,4))

b) Tensors计算

x = torch.Tensor([[1,2],[3,4]])
y = torch.Tensor([[5,6],[7,8]])
z = x+y

c) Reshape Tensors

x = torch.randn(2,3,4)
#拉直
x = x.view(-1)
#4*6维度
x = x.view(4,6)

2)计算图和自动微分

a) Variable变量

#将Tensor变为Variable
x = autograd.Variable(torch.Tensor([1,2,3]),requires_grad = True)
#将Variable变为Tensor
y = x.data

b) 反向梯度算法

x = autograd.Variable(torch.Tensor([1,2]),requires_grad=True)
y = autograd.Variable(torch.Tensor([3,4]),requires_grad=True)
z = x+y
#求和
s = z.sum()
#反向梯度传播
s.backward()
print(x.grad)

c) 线性映射

linear = nn.Linear(3,5) #三维线性映射到五维
x = autograd.Variable(torch.randn(4,3))
#输出为(4,5)维
y = linear(x)

d) 非线性映射(激活函数的使用)

x = autograd.Variable(torch.randn(5))
#relu激活函数
x_relu = F.relu(x)
print(x_relu)
x_soft = F.softmax(x)
#softmax激活函数
print(x_soft)
print(x_soft.sum())

output:

Variable containing:
-0.9347
-0.9882
 1.3801
-0.1173
 0.9317
[torch.FloatTensor of size 5]
 
Variable containing:
 0.0481
 0.0456
 0.4867
 0.1089
 0.3108
[torch.FloatTensor of size 5]
 
Variable containing:
 1
[torch.FloatTensor of size 1]
 
Variable containing:
-3.0350
-3.0885
-0.7201
-2.2176
-1.1686
[torch.FloatTensor of size 5]

二、Pytorch创建网络

1) word embedding词嵌入

通过nn.Embedding(m,n)实现,m表示所有的单词数目,n表示词嵌入的维度。

word_to_idx = {'hello':0,'world':1}
embeds = nn.Embedding(2,5) #即两个单词,单词的词嵌入维度为5
hello_idx = torch.LongTensor([word_to_idx['hello']])
hello_idx = autograd.Variable(hello_idx)
hello_embed = embeds(hello_idx)
print(hello_embed)

output:

Variable containing:
-0.6982 0.3909 -1.0760 -1.6215 0.4429
[torch.FloatTensor of size 1x5]

2) N-Gram 语言模型

先介绍一下N-Gram语言模型,给定一个单词序列 ,计算 ,其中 是序列的第 个单词。

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import torch.optim as optim
 
from six.moves import xrange

对句子进行分词:

context_size = 2
embed_dim = 10
text_sequence = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say, within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserv'd thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse,'
Proving his beauty by succession thine!
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.""".split()
#分词
trigrams = [ ([text_sequence[i], text_sequence[i+1]], text_sequence[i+2]) for i in xrange(len(text_sequence) - 2) ]
trigrams[:10]

分词的形式为:

Pytorch在NLP中的简单应用详解

#建立vocab索引
vocab = set(text_sequence)
word_to_ix = {word: i for i,word in enumerate(vocab)}

建立N-Gram Language model

#N-Gram Language model
class NGramLanguageModeler(nn.Module): 
 def __init__(self, vocab_size, embed_dim, context_size):
  super(NGramLanguageModeler, self).__init__()
  #词嵌入
  self.embedding = nn.Embedding(vocab_size, embed_dim)
  #两层线性分类器
  self.linear1 = nn.Linear(embed_dim*context_size, 128)
  self.linear2 = nn.Linear(128, vocab_size)
  
 def forward(self, input):
  embeds = self.embedding(input).view((1, -1)) #2,10拉直为20
  out = F.relu(self.linear1(embeds))
  out = F.relu(self.linear2(out))
  log_probs = F.log_softmax(out)
  return log_probs

输出模型看一下网络结构

#输出模型看一下网络结构
model = NGramLanguageModeler(96,10,2)
print(model)

Pytorch在NLP中的简单应用详解

定义损失函数和优化器

#定义损失函数以及优化器
loss_function = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(),lr = 0.01)
model = NGramLanguageModeler(len(vocab), embed_dim, context_size)
losses = []

模型训练

#模型训练
for epoch in xrange(10):
 total_loss = torch.Tensor([0])
 for context, target in trigrams:
  #1.处理数据输入为索引向量
  #print(context)
  #注:python3中map函数前要加上list()转换为列表形式
  context_idxs = list(map(lambda w: word_to_ix[w], context))
  #print(context_idxs)
  context_var = autograd.Variable( torch.LongTensor(context_idxs) )
 
  
  #2.梯度清零
  model.zero_grad()
  
  #3.前向传播,计算下一个单词的概率
  log_probs = model(context_var)
  
  #4.损失函数
  loss = loss_function(log_probs, autograd.Variable(torch.LongTensor([word_to_ix[target]])))
  
  #反向传播及梯度更新
  loss.backward()
  optimizer.step()
  
  total_loss += loss.data 
 losses.append(total_loss)
print(losses)

以上这篇Pytorch在NLP中的简单应用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之使用Python查询更新数据库
Nov 25 Python
python操作sqlite的CRUD实例分析
May 08 Python
python3使用PyMysql连接mysql数据库实例
Feb 07 Python
python分布式环境下的限流器的示例
Oct 26 Python
Python简单实现的代理服务器端口映射功能示例
Apr 08 Python
Python中文件的读取和写入操作
Apr 27 Python
python读取各种文件数据方法解析
Dec 29 Python
Python制作exe文件简单流程
Jan 24 Python
python制作简单五子棋游戏
Jun 18 Python
Python hashlib模块加密过程解析
Nov 05 Python
python GUI库图形界面开发之PyQt5窗口布局控件QStackedWidget详细使用方法
Feb 27 Python
Python pymysql模块安装并操作过程解析
Oct 13 Python
解析PyCharm Python运行权限问题
Jan 08 #Python
python读取ini配置的类封装代码实例
Jan 08 #Python
Python Des加密解密如何实现软件注册码机器码
Jan 08 #Python
Pytorch技巧:DataLoader的collate_fn参数使用详解
Jan 08 #Python
Pytorch DataLoader 变长数据处理方式
Jan 08 #Python
pytorch实现用CNN和LSTM对文本进行分类方式
Jan 08 #Python
使用pytorch和torchtext进行文本分类的实例
Jan 08 #Python
You might like
PHP下几种删除目录的方法总结
2007/08/19 PHP
浅析ThinkPHP的模板输出功能
2014/07/01 PHP
支持汉转拼和拼音分词的PHP中文工具类ChineseUtil
2018/02/23 PHP
PHP实现的多维数组去重操作示例
2018/07/21 PHP
javascript实现信息的显示和隐藏如注册页面
2013/12/03 Javascript
node.js中的fs.stat方法使用说明
2014/12/16 Javascript
jQuery实现向下滑出的平滑下拉菜单效果
2015/08/21 Javascript
基于Bootstrap实现Material Design风格表单插件 附源码下载
2016/04/18 Javascript
jQuery实现微信长按识别二维码功能
2016/08/26 Javascript
简单理解vue中track-by属性
2016/10/26 Javascript
封装运动框架实战左右与上下滑动的焦点轮播图(实例)
2017/10/17 Javascript
基于node.js实现爬虫的讲解
2019/02/18 Javascript
微信小程序通过js实现瀑布流布局详解
2019/08/28 Javascript
mpvue网易云短信接口实现小程序短信登录的示例代码
2020/04/03 Javascript
Vue页面手动刷新,实现导航栏激活项还原到初始状态
2020/08/06 Javascript
[04:47]DOTA2-潍坊风行电子俱乐部探秘
2014/08/08 DOTA
python中列表元素连接方法join用法实例
2015/04/07 Python
Python实现简单的四则运算计算器
2016/11/02 Python
Python实现的简单dns查询功能示例
2017/05/24 Python
利用python将图片转换成excel文档格式
2017/12/30 Python
python实现自动登录后台管理系统
2018/10/18 Python
python3 实现一行输入,空格隔开的示例
2018/11/14 Python
Python列表切片操作实例总结
2019/02/19 Python
python实现微信小程序用户登录、模板推送
2019/08/28 Python
树莓派4B+opencv4+python 打开摄像头的实现方法
2019/10/18 Python
SpringBoot实现登录注册常见问题解决方案
2020/03/04 Python
Anaconda和ipython环境适配的实现
2020/04/22 Python
Python map及filter函数使用方法解析
2020/08/06 Python
美国棒球装备和用品商店:Baseball Savings
2018/06/09 全球购物
澳大利亚儿童鞋在线:The Trybe
2019/07/16 全球购物
院药学专业个人求职信
2013/09/21 职场文书
房地产开发计划书
2014/01/10 职场文书
领导班子党的群众路线教育实践活动对照检查材料
2014/09/25 职场文书
2014年民主评议党员工作总结
2014/12/02 职场文书
物业项目经理岗位职责
2015/04/01 职场文书
汽车质检员岗位职责
2015/04/08 职场文书