前言
这周学习一个用PyTorch实现的序列到序列(Sequence to Sequence, Seq2Seq)模型。这种模型广泛应用于机器翻译、文本生成等自然语言处理任务中。下面将详细解释代码的结构和一些关键函数的实现。
引入所需库
首先,引入了必要的库和模块:
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)
device
用来确定是否使用GPU,如果有可用的GPU,代码将使用GPU进行训练,否则使用CPU。
语言类定义
接下来,定义了一个语言类Lang
,用于处理语言相关的数据结构:
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
类主要用于构建词汇表,将句子中的单词转换为索引,并统计每个单词的出现次数。
数据预处理函数
为了处理输入的文本数据,定义了几个预处理函数:
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
这些函数用于将Unicode字符串转换为ASCII,并进行一些基本的规范化处理,如去除标点符号和非字母字符。
读取数据并创建语言类实例
def readLangs(lang1, lang2, reverse=False):
print("Reading lines...")
lines = open('%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
这个函数从文件中读取双语句子对,并根据需要反转输入和输出语言。
数据过滤与准备
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