第N8周:seq2seq翻译实战-Pytorch复现

  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊 | 接辅导、项目定制

一、前期准备

from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import string
import re
import random
 
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
 
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

1、搭建语言类

SOS_token = 0
EOS_token = 1
 
# 语言类,方便对语料库进行操作
class Lang:
    def __init__(self, name):
        self.name = name
        self.word2index = {}
        self.word2count = {}
        self.index2word = {0: "SOS", 1: "EOS"}
        self.n_words    = 2  # Count SOS and EOS
 
    def addSentence(self, sentence):
        for word in sentence.split(' '):
            self.addWord(word)
 
    def addWord(self, word):
        if word not in self.word2index:
            self.word2index[word] = self.n_words
            self.word2count[word] = 1
            self.index2word[self.n_words] = word
            self.n_words += 1
        else:
            self.word2count[word] += 1

定义了一个名为Lang的类,用于处理语料库。Lang类包含了两个函数,addSentence和addWord,用于向语料库中添加句子和单词。类中包含了一些属性,word2index、word2count、index2word、n_words,分别用于存储单词到索引的映射、单词累计次数、索引到单词的映射以及单词总数。

2、文本处理函数 

def unicodeToAscii(s):
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn'
    )
 
# 小写化,剔除标点与非字母符号
def normalizeString(s):
    s = unicodeToAscii(s.lower().strip())
    s = re.sub(r"([.!?])", r" \1", s)
    s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
    return s

unicodeToAscii 函数的通过使用 unicodedata.normalize('NFD', s) 将字符串进行规范化分解,然后通过列表推导式保留所有不属于 'Mn' 类别的字符,最后将这些字符拼接成一个新的字符串返回。

normalizeString 函数先调用 unicodeToAscii 函数将输入的字符串转换为 ASCII 字符串,然后使用正则表达式替换掉所有的句号、感叹号和问号,以及所有非字母、非空格、非句号、非感叹号、非问号的字符,最后返回处理后的字符串。

3、文件读取函数 

def readLangs(lang1,lang2,reverse=False):
    print("Reading lines...")
    
    lines = open('D:/%s-%s.txt'%(lang1,lang2),encoding='utf-8').\
            read().strip().split('\n')
    
    pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
    
    if reverse:
        pairs       =[list(reversed(p)) for p in pairs]
        input_lang  = Lang(lang2)
        output_lang =Lang(lang1)
    else:
        input_lang  =Lang(lang1)
        output_lang =Lang(lang2)
        
    return input_lang,output_lang,pairs

readLangs接受三个参数:lang1lang2reverse。函数的主要功能是从一个文本文件中读取语言对数据,并根据需要对数据进行预处理。

MAX_LENGTH = 10      # 定义语料最长长度
 
eng_prefixes = (
    "i am ", "i m ",
    "he is", "he s ",
    "she is", "she s ",
    "you are", "you re ",
    "we are", "we re ",
    "they are", "they re "
)
 
def filterPair(p):
    return len(p[0].split(' ')) < MAX_LENGTH and \
           len(p[1].split(' ')) < MAX_LENGTH and p[1].startswith(eng_prefixes)
 
def filterPairs(pairs):
    # 选取仅仅包含 eng_prefixes 开头的语料
    return [pair for pair in pairs if filterPair(pair)]

 

def prepareData(lang1,lang2,reverse=False):
    input_lang,output_lang,pairs = readLangs(lang1,lang2,reverse)
    print("Read %s sentence pairs" % len(pairs))
    
    pairs = filterPairs(pairs[:])
    print("Trimmed to %s sentence pairs" % len(pairs))
    print("Counting words...")
    
    for pair in pairs:
        input_lang.addSentence(pair[0])
        output_lang.addSentence(pair[1])
        
    print ("Counted words:")
    print(input_lang.name,input_lang.n_words)
    print(output_lang.name,output_lang.n_words)
    return input_lang, output_lang,pairs
 
input_lang,output_lang,pairs = prepareData('eng','fra',True)
print(random.choice(pairs))

二、Seq2Seq模型 

1.编码器(Encoder)

class EncoderRNN(nn.Module):
    def __init__(self, input_size, hidden_size):
        super(EncoderRNN, self).__init__()
        self.hidden_size = hidden_size
        self.embedding   = nn.Embedding(input_size, hidden_size)
        self.gru         = nn.GRU(hidden_size, hidden_size)
 
    def forward(self, input, hidden):
        embedded       = self.embedding(input).view(1, 1, -1)
        output         = embedded
        output, hidden = self.gru(output, hidden)
        return output, hidden
 
    def initHidden(self):
        return torch.zeros(1, 1, self.hidden_size, device=device)

2.解码器(Decoder)

class DecoderRNN(nn.Module):
    def __init__(self, hidden_size, output_size):
        super(DecoderRNN, self).__init__()
        self.hidden_size = hidden_size
        self.embedding   = nn.Embedding(output_size, hidden_size)
        self.gru         = nn.GRU(hidden_size, hidden_size)
        self.out         = nn.Linear(hidden_size, output_size)
        self.softmax     = nn.LogSoftmax(dim=1)
 
    def forward(self, input, hidden):
        output         = self.embedding(input).view(1, 1, -1)
        output         = F.relu(output)
        output, hidden = self.gru(output, hidden)
        output         = self.softmax(self.out(output[0]))
        return output, hidden
 
    def initHidden(self):
        return torch.zeros(1, 1, self.hidden_size, device=device)

三、训练

1.数据预处理

#将句子中的每个单词转换为对应的索引值,并将这些索引值存储在一个列表中。
def indexesFromSentence(lang, sentence):
    return [lang.word2index[word] for word in sentence.split(' ')]

 
# 将数字化的文本,转化为tensor数据
def tensorFromSentence(lang, sentence):
    indexes = indexesFromSentence(lang, sentence)
    indexes.append(EOS_token)
    return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)
 
# 输入pair文本,输出预处理好的数据
def tensorsFromPair(pair):
    input_tensor  = tensorFromSentence(input_lang, pair[0])
    target_tensor = tensorFromSentence(output_lang, pair[1])
    return (input_tensor, target_tensor)

2.训练函数

teacher_forcing_ratio = 0.5
 
def train(input_tensor, target_tensor, 
          encoder, decoder, 
          encoder_optimizer, decoder_optimizer, 
          criterion, max_length=MAX_LENGTH):
    
    # 编码器初始化
    encoder_hidden = encoder.initHidden()
    
    # grad属性归零
    encoder_optimizer.zero_grad()
    decoder_optimizer.zero_grad()
 
    input_length  = input_tensor.size(0)
    target_length = target_tensor.size(0)
    
    # 用于创建一个指定大小的全零张量(tensor),用作默认编码器输出
    encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)
 
    loss = 0
    
    # 将处理好的语料送入编码器
    for ei in range(input_length):
        encoder_output, encoder_hidden = encoder(input_tensor[ei], encoder_hidden)
        encoder_outputs[ei]            = encoder_output[0, 0]
    
    # 解码器默认输出
    decoder_input  = torch.tensor([[SOS_token]], device=device)
    decoder_hidden = encoder_hidden
 
    use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False
    
    # 将编码器处理好的输出送入解码器
    if use_teacher_forcing:
        # Teacher forcing: Feed the target as the next input
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden)
            
            loss         += criterion(decoder_output, target_tensor[di])
            decoder_input = target_tensor[di]  # Teacher forcing
    else:
        # Without teacher forcing: use its own predictions as the next input
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden)
            
            topv, topi    = decoder_output.topk(1)
            decoder_input = topi.squeeze().detach()  # detach from history as input
 
            loss         += criterion(decoder_output, target_tensor[di])
            if decoder_input.item() == EOS_token:
                break
 
    loss.backward()
 
    encoder_optimizer.step()
    decoder_optimizer.step()
 
    return loss.item() / target_length

在序列生成的任务中,如机器翻译或文本生成,解码器(decoder)的输入通常是由解码器自己生成的预测结果,即前一个时间步的输出。然而,这种自回归方式可能存在一个问题,即在训练过程中,解码器可能会产生累积误差,并导致输出与目标序列逐渐偏离。
为了解决这个问题,引入了一种称为"Teacher Forcing"的技术。在训练过程中,Teacher Forcing将目标序列的真实值作为解码器的输入,而不是使用解码器自己的预测结果。这样可以提供更准确的指导信号,帮助解码器更快地学习到正确的输出。
在这段代码中,use_teacher_forcing变量用于确定解码器在训练阶段使用何种策略作为下一个输入。
当use_teacher_forcing为True时,采用"Teacher Forcing"的策略,即将目标序列中的真实标签作为解码器的下一个输入。而当use_teacher_forcing为False时,采用"Without Teacher Forcing"的策略,即将解码器自身的预测作为下一个输入。

import time
import math
 
def asMinutes(s):
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)
 
def timeSince(since, percent):
    now = time.time()
    s = now - since
    es = s / (percent)
    rs = es - s
    return '%s (- %s)' % (asMinutes(s), asMinutes(rs))
def trainIters(encoder,decoder,n_iters,print_every=1000,
               plot_every=100,learning_rate=0.01):
    
    start = time.time()
    plot_losses      = []
    print_loss_total = 0  # Reset every print_every
    plot_loss_total  = 0  # Reset every plot_every
 
    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)
    
    # 在 pairs 中随机选取 n_iters 条数据用作训练集
    training_pairs    = [tensorsFromPair(random.choice(pairs)) for i in range(n_iters)]
    criterion         = nn.NLLLoss()
 
    for iter in range(1, n_iters + 1):
        training_pair = training_pairs[iter - 1]
        input_tensor  = training_pair[0]
        target_tensor = training_pair[1]
 
        loss = train(input_tensor, target_tensor, encoder,
                     decoder, encoder_optimizer, decoder_optimizer, criterion)
        print_loss_total += loss
        plot_loss_total  += loss
 
        if iter % print_every == 0:
            print_loss_avg   = print_loss_total / print_every
            print_loss_total = 0
            print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),
                                         iter, iter / n_iters * 100, print_loss_avg))
 
        if iter % plot_every == 0:
            plot_loss_avg = plot_loss_total / plot_every
            plot_losses.append(plot_loss_avg)
            plot_loss_total = 0
 
    return plot_losses

四、训练与评估

hidden_size   = 256
encoder1      = EncoderRNN(input_lang.n_words, hidden_size).to(device)
attn_decoder1 = DecoderRNN(hidden_size, output_lang.n_words).to(device)
 
plot_losses = trainIters(encoder1, attn_decoder1, 100000, print_every=5000)

 

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               # 忽略警告信息
# plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        # 分辨率
 
epochs_range = range(len(plot_losses))
 
plt.figure(figsize=(8, 3))
 
plt.subplot(1, 1, 1)
plt.plot(epochs_range, plot_losses, label='Training Loss')
plt.legend(loc='upper right')
plt.title('Training Loss')
plt.show()

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

DataGrip 2024 po for Mac 数据库管理工具解

Mac分享吧 文章目录 效果一、下载软件二、开始安装1、双击运行软件&#xff08;适合自己的M芯片版或Intel芯片版&#xff09;&#xff0c;将其从左侧拖入右侧文件夹中&#xff0c;等待安装完毕2、应用程序显示软件图标&#xff0c;表示安装成功3、打开访达&#xff0c;点击【文…

怎么实现微信支付?

微信小程序中微信支付&#xff08;前端流程&#xff09; 微信支付前准备工作 微信公众平台绑定商户号 微信支付平台配置好后端信息支付前要有用户的openid 1. 客户端点击支付按钮 在用户点击支付按钮时&#xff0c;触发支付流程。 // 绑定支付按钮点击事件 function onPayB…

前端 CSS 经典:图层放大的 hover 效果

效果 思路 设置 3 层元素&#xff0c;最上层元素使用 clip-path 裁剪成圆&#xff0c;hover 改变圆大小&#xff0c;添加过渡效果。 实现代码 <!DOCTYPE html> <html lang"en"><head><meta charset"utf-8" /><meta http-eq…

基于matlab的K-means聚类图像分割

1 原理 K-means聚类算法在图像分割中的应用是基于一种无监督的学习方法&#xff0c;它将图像中的像素点或特征区域划分为K个不同的簇或类别。以下是K-means聚类算法用于图像分割的原理&#xff0c;包括步骤和公式&#xff1a; 1.1 原理概述 选择簇的数量(K)&#xff1a; 首先…

Android 多媒体开发——Media3与MediaSession最全使用指南

一、Media3库简介 1.1 Media3是什么&#xff1f; 官方释义&#xff1a; Jetpack Media3 is the new home for media libraries that enables Android apps to display rich audio and visual experiences. Media3 offers a simple architecture with powerful customization,…

为什么部署数字人系统源码一定要找源头工厂?

随着人工智能技术的发展成熟&#xff0c;数字人的应用场景被不断拓展&#xff0c;从而让更多人看到了数字人所蕴含的前景和潜力。于是&#xff0c;越来越多的创业者开始找数字人源头工厂进行数字人源码部署&#xff0c;以打造自己的数字人系统。许多骗子也因此看到了可乘之机&a…

SK Hynix 3D DRAM良率突破56.1%,开启存储新时代

根据韩国财经媒体Business Korea独家报道&#xff1a;在刚刚结束的VLSI 2024国际研讨会上&#xff0c;韩国半导体巨头SK Hynix公布了一项振奋人心的进展&#xff1a;其五层堆叠3D DRAM的制造良率已达到56.1%。此成果标志着3D DRAM技术在商业化道路上迈出了坚实的一步&#xff0…

【python】eval函数

1.eval函数的语法及用法 &#xff08;1&#xff09;语法&#xff1a;eval(expression) 参数说明&#xff1a; expression&#xff1a;必须为字符串表达式&#xff0c;可为算法&#xff0c;也可为input函数等。 说明&#xff1a;表达式必需是字符串&#xff0c;否则会报错&a…

【Text2SQL 论文】MCS-SQL:利用多样 prompts + 多项选择来做 Text2SQL

论文&#xff1a;MCS-SQL: Leveraging Multiple Prompts and Multiple-Choice Selection For Text-to-SQL Generation ⭐⭐⭐ arXiv:2405.07467 一、论文速读 已有研究指出&#xff0c;在使用 LLM 使用 ICL 时&#xff0c;ICL 的 few-shot exemplars 的内容、呈现顺序都会敏感…

大自然高清风景视频无水印素材在哪下载?下载视频素材网分享

在视频创作领域&#xff0c;一段高清的风景视频可以极大地提升你的作品质感。无论是作为背景、过渡片段还是主要内容&#xff0c;优质的风景视频素材都是必不可少的。然而&#xff0c;寻找既高清又无水印的风景视频素材并非易事。为了帮助大家轻松获取这类素材&#xff0c;我整…

计算机缺失d3dx9_43.dll的多种解决方法,哪种更推荐使用

我在使用计算机时遇到了一个问题&#xff0c;系统提示我丢失了d3dx9_43.dll文件。丢失d3dx9_43.dll文件通常是由于DirectX组件未正确安装或损坏所致&#xff0c;这直接影响到依赖于DirectX的游戏和应用的运行。经过一番搜索和尝试&#xff0c;我找到了多种修复这个问题的方法&a…

突然断供中国!OpenAI变CloseAI,用户连夜搬家

ChatGPT狂飙160天&#xff0c;世界已经不是之前的样子。 更多资源欢迎关注 OpenAI&#xff0c;这把变成CloseAI了。 6月25日早上&#xff0c;有中国开发者表示收到了来自OpenAI的“警告信”&#xff1a;将采取额外措施停止其不支持的地区的API&#xff08;应用接口&#xff09…

typescript学习回顾(二)

今天来分享一下ts的基础&#xff0c;如何使用ts&#xff0c;以及ts具体的作用&#xff0c;如何去约束我们开发中常见的一些数据的&#xff0c;最后做一个小练习来巩固对ts基础的掌握程度。 类型约束 如何加类型约束呢 变量、函数的参数、函数的返回值位置加上:类型 比如 //约…

微信小程序-自定义组件checkbox

一.自定义Coponent组件 公共组件&#xff1a;将页面内公共的模块抽取为自定义组件&#xff0c;在不同页面复用。 页面组件&#xff1a;将复杂页面进行拆分&#xff0c;降低耦合度&#xff0c;有利于代码维护。 可以新建文件夹component放组件&#xff1a; 组件名为custom-che…

msvcr110.dll丢失的解决方法,亲测有效的几种解决方法

最近&#xff0c;我在启动一个程序时&#xff0c;系统突然弹出一个错误提示&#xff0c;告诉我电脑缺失了一个名为msvcr110.dll的文件。这让我感到非常困惑&#xff0c;因为我之前从未遇到过这样的问题。经过一番搜索和尝试&#xff0c;我总结了5种靠谱的解决方法。下面分享给大…

1.k8s:架构,组件,基础概念

目录 一、k8s了解 1.什么是k8s 2.为什么要k8s &#xff08;1&#xff09;部署方式演变 &#xff08;2&#xff09;k8s作用 &#xff08;3&#xff09;Mesos&#xff0c;Swarm&#xff0c;K8S三大平台对比 二、k8s架构、组件 1.k8s架构 2.k8s基础组件 3.k8s附加组件 …

【2024最新版】Eclipse安装配置全攻略:图文详解

目录 1. Eclipse介绍1.1 背景1.2 主要特点和功能1.3 版本发布1.4 优势与劣势 2. 下载Eclipse3. 安装Eclipse4. 启动Eclipse 1. Eclipse介绍 Eclipse是一个开源的、基于Java的可扩展开发平台&#xff0c;主要用于Java开发者&#xff0c;但也支持其他语言如C/C、PHP、Python等。…

CCS的安装步骤

CCS的安装步骤 安装之前有几件重要的事情要做&#xff1a; 首先肯定是要下载安装包啦&#xff01;点击此处是跳到官网下载地址安装包不能处的路径中不能包含中文关闭病毒防护和防火墙&#xff0c;以及其他杀毒软件最后是在重启后进行安装 主要的步骤如下&#xff1a; 找到安…

【SpringBoot Web框架实战教程(开源)】01 使用 pom 方式创建 SpringBoot 第一个项目

导读 这是一系列关于 SpringBoot Web框架实战 的教程&#xff0c;从项目的创建&#xff0c;到一个完整的 web 框架&#xff08;包括异常处理、拦截器、context 上下文等&#xff09;&#xff1b;从0开始&#xff0c;到一个可以直接运用在生产环境中的web框架。而且所有源码均开…

202485读书笔记|《我还有一片风景要完成》——溪水急着要流向海洋 浪潮却渴望重回土地 弱水长流,我只能尽一瓢饮,世界大千,我只能作一瞬观

202485读书笔记|《我还有一片风景要完成》——溪水急着要流向海洋 浪潮却渴望重回土地 弱水长流&#xff0c;我只能尽一瓢饮&#xff0c;世界大千&#xff0c;我只能作一瞬观 《华语散文温柔的一支笔&#xff1a;张晓风作品集&#xff08;共5册&#xff09;》张晓风&#xff0c…