在这个部分,我们的目标是给一些提示,最后生成一个名字
Preparing Data 与第一个 部分一样,我们先要对数据进行处理,数据处理的流程如下:(个人认为数据处理是很重要的一个部分,而且数据的多种多样也给数据处理带来了很大的困难,还是要努力提升自己的能力才能够得心应手)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 from io import import open import glob import osimport unicodedata import string all_letters = string.ascii_letters + " .,;'-" n_letters = len (all_letters) + 1 def findFiles (path ): return glob.glob(path)def unicodeToAscii (s ): return '' .join( c for c in unicodedata.normalize('NFD' , s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def readLines (filename ): with open (filename, encoding='utf-8' ) as some_file: return [unicodeToAscii(line.strip()) for line in some_file] category_lines = {} all_categories = [] for filename in findFiles('data/names/*.txt' ): category = os.path.splitext(os.path.basename(filename))[0 ] all_categories.append(category) lines = readLines(filename) category_lines[category] = lines n_categories = len (all_categories) if n_categories == 0 : raise RuntimeError('未找到数据。请确保已从 ' 'https://download.pytorch.org/tutorial/data.zip 下载数据 ' '并解压到当前目录。' ) print ('类别数量:' , n_categories, all_categories)print (unicodeToAscii("O'Néàl" ))
Creating the Network 这个网络用category张量的额外参数扩展了上一个教程的RNN,该参数与其他张量一起连接在一起。category张量是一个one-hot vector,就像字母输入一样。
我们将把输出解释为下一个字母的概率。抽样时,最有可能的输出字母被用作下一个输入字母。
添加了第二个线性层o2o(在结合隐藏和输出后),使其有更多的力量来工作。还有一个dropout 层,它以给定的概率(这里为0.1)随机归零其输入的一部分,通常用于模糊输入,以防止过度拟合。在这里,我们在网络结束时使用它,故意增加一些混乱并增加采样多样性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import torch import torch.nn as nn class RNN (nn.Module): def __init__ (self, input_size, hidden_size, output_size ): super (RNN, self ).__init__() self .hidden_size = hidden_size self .i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size) self .i2o = nn.Linear(n_categories + input_size + hidden_size, output_size) self .o2o = nn.Linear(hidden_size + output_size, output_size) self .dropout = nn.Dropout(0.1 ) self .softmax = nn.LogSoftmax(dim=1 ) def forward (self, category, input , hidden ): input_combined = torch.cat((category, input , hidden), 1 ) hidden = self .i2h(input_combined) output = self .i2o(input_combined) output_combined = torch.cat((hidden, output), 1 ) output = self .o2o(output_combined) output = self .dropout(output) output = self .softmax(output) return output, hidden def initHidden (self ): return torch.zeros(1 , self .hidden_size)
Training
首先我们创建一个随机生成的输入对(category, line)
1 2 3 4 5 6 7 8 9 10 11 import random def randomChoice (l ): return l[random.randint(0 , len (l) - 1 )] def randomTrainingPair (): category = randomChoice(all_categories) line = randomChoice(category_lines[category]) return category, line
对于每个时间步骤(即训练单词中的每个字母),网络的输入将是(category、current letter、hidden state),输出将是(next letter,next hidden state)。因此,对于每个训练集,我们需要类别、一组输入字母和一组输出/目标字母。
由于我们正在预测每个时间步骤的当前字母的下一个字母,字母对是行中的连续字母组——例如,对于“ABCD<EOS>”,我们将创建(“A”、“B”)、(“B”、“C”)、(“C”、“D”)、(“D”、“EOS”)。
category tensor是大小为<1 x n_categories>的 one-hot vector。在训练时,我们在每个时间步骤中将其输入网络,它本可以作为初始隐藏状态或其他策略的一部分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 def categoryTensor (category ): li = all_categories.index(category) tensor = torch.zeros(1 , n_categories) tensor[0 ][li] = 1 return tensor def inputTensor (line ): tensor = torch.zeros(len (line), 1 , n_letters) for li in range (len (line)): letter = line[li] tensor[li][0 ][all_letters.find(letter)] = 1 return tensor def targetTensor (line ): letter_indexes = [all_letters.find(line[li]) for li in range (1 , len (line))] letter_indexes.append(n_letters - 1 ) return torch.LongTensor(letter_indexes) def randomTrainingExample (): category, line = randomTrainingPair() category_tensor = categoryTensor(category) input_line_tensor = inputTensor(line) target_line_tensor = targetTensor(line) return category_tensor, input_line_tensor, target_line_tensor
Training the Network
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 criterion = nn.NLLLoss() learning_rate = 0.0005 def train (category_tensor, input_line_tensor, target_line_tensor ): target_line_tensor.unsqueeze_(-1 ) hidden = rnn.initHidden() rnn.zero_grad() loss = torch.Tensor([0 ]) for i in range (input_line_tensor.size(0 )): output, hidden = rnn(category_tensor, input_line_tensor[i], hidden) l = criterion(output, target_line_tensor[i]) loss += l loss.backward() for p in rnn.parameters(): p.data.add_(p.grad.data, alpha=-learning_rate) return output, loss.item() / input_line_tensor.size(0 )
添加一个时间记录的函数来统计模型训练的时间:
1 2 3 4 5 6 7 8 9 import timeimport mathdef timeSince (since ): now = time.time() s = now - since m = math.floor(s / 60 ) s -= m * 60 return '%dm %ds' % (m, s)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 rnn = RNN(n_letters, 128 , n_letters) n_iters = 100000 print_every = 5000 plot_every = 500 all_losses = [] total_loss = 0 start = time.time() for iter in range (1 , n_iters + 1 ): output, loss = train(*randomTrainingExample()) total_loss += loss if iter % print_every == 0 : print ('%s (%d %d%%) %.4f' % (timeSince(start), iter , iter / n_iters * 100 , loss)) if iter % plot_every == 0 : all_losses.append(total_loss / plot_every) total_loss = 0
绘制损失函数:
1 2 3 4 import matplotlib.pyplot as pltplt.figure() plt.plot(all_losses)
结果测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 max_length = 20 def sample (category, start_letter='A' ): with torch.no_grad(): category_tensor = categoryTensor(category) input = inputTensor(start_letter) hidden = rnn.initHidden() output_name = start_letter for i in range (max_length): output, hidden = rnn(category_tensor, input [0 ], hidden) topv, topi = output.topk(1 ) topi = topi[0 ][0 ] if topi == n_letters - 1 : break else : letter = all_letters[topi] output_name += letter input = inputTensor(letter) return output_name def samples (category, start_letters='ABC' ): for start_letter in start_letters: print (sample(category, start_letter)) samples('Russian' , 'RUS' ) samples('German' , 'GER' ) samples('Spanish' , 'SPA' ) samples('Chinese' , 'CHI' )