字符级RNN生成名称!🌞

字符级RNN生成名称

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from io import open
import glob
import os
import unicodedata
import string

all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1 # Plus EOS marker

def findFiles(path): return glob.glob(path)

# Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
and c in all_letters
)

# Read a file and split into lines
def readLines(filename):
with open(filename, encoding='utf-8') as some_file:
return [unicodeToAscii(line.strip()) for line in some_file]

# Build the category_lines dictionary, a list of lines per category
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('Data not found. Make sure that you downloaded data '
'from https://download.pytorch.org/tutorial/data.zip and extract it to '
'the current directory.')

print('# categories:', n_categories, all_categories)
print(unicodeToAscii("O'Néàl"))

2.创建网络

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)

tIps:

该网络与之前的实战网络有一定区别。

3.训练

首先,帮助函数获取随机对(类别,行):

1
2
3
4
5
6
7
8
9
10
11
import random

# Random item from a list
def randomChoice(l):
return l[random.randint(0, len(l) - 1)]

# Get a random category and random line from that category
def randomTrainingPair():
category = randomChoice(all_categories)
line = randomChoice(category_lines[category])
return category, line

对于每个时间步(即,对于训练词中的每个字母),网络的输入将是(category, current letter, hidden state),输出将是(next letter, next hidden state)

类别张量是大小 <1 x n_categories> 为 的单热张量。在训练时,我们会在每个时间步将其馈送到网络 - 这是一种设计选择,它可以作为初始隐藏状态或其他策略的一部分包含在内。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# One-hot vector for category
def categoryTensor(category):
li = all_categories.index(category)
tensor = torch.zeros(1, n_categories)
tensor[0][li] = 1
return tensor

# One-hot matrix of first to last letters (not including EOS) for input
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

# ``LongTensor`` of second letter to end (EOS) for target
def targetTensor(line):
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
letter_indexes.append(n_letters - 1) # EOS
return torch.LongTensor(letter_indexes)

为了方便起见,在训练过程中,我们将创建一个 randomTrainingExample 函数来获取随机(类别、行)对并将它们转换为所需的(类别、输入、目标)张量。

1
2
3
4
5
6
7
# Make category, input, and target tensors from a random category, line pair
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

4.训练网络

与仅使用最后一个输出的分类相反,我们在每一步都进行预测,因此我们正在计算每一步的损失。

autograd 的魔力允许您简单地将每一步的这些损失相加,并在最后向后调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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]) # you can also just simply use ``loss = 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)

tips:

在PyTorch中,要实现将多个损失函数相加然后一起向后传播,你可以简单地将这些损失函数的结果相加,然后调用backward()函数来进行反向传播。下面是一个示例:

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
import torch
import torch.nn as nn
import torch.optim as optim

# 假设有两个损失函数
criterion1 = nn.CrossEntropyLoss()
criterion2 = nn.MSELoss()

# 模拟输入数据和目标数据
inputs = torch.randn(10, 5) # 示例输入数据,假设有10个样本,每个样本有5个特征
targets1 = torch.empty(10, dtype=torch.long).random_(5) # 示例目标数据1
targets2 = torch.randn(10, 1) # 示例目标数据2

# 假设有一个模型
model = nn.Linear(5, 2) # 示例模型,输入维度为5,输出维度为2

# 假设有一个优化器
optimizer = optim.SGD(model.parameters(), lr=0.01)

# 前向传播
outputs = model(inputs)

# 计算损失
loss1 = criterion1(outputs, targets1)
loss2 = criterion2(outputs, targets2)

# 将损失相加
total_loss = loss1 + loss2

# 反向传播
optimizer.zero_grad()
total_loss.backward()

# 更新参数
optimizer.step()

在这种情况下,将两个损失函数相加然后一起进行反向传播和分别计算每个损失函数然后分开进行反向传播是不完全一样的。

  1. 将两个损失函数相加然后一起进行反向传播:这种方法会将两个损失函数的梯度相加,然后一次性更新模型参数。这意味着模型的参数在一次优化步骤中同时考虑了两个损失函数的信息。
  2. 分别计算每个损失函数然后分开进行反向传播:这种方法会分别计算每个损失函数的梯度,并分别调用backward()函数进行反向传播,然后根据每个损失函数的梯度更新模型参数。这意味着模型的参数在每个优化步骤中分别考虑每个损失函数的信息。

通常情况下,这两种方法可能会得到不同的结果,尤其是在存在参数共享或者不同损失函数的梯度具有不同的量级时。在某些情况下,将两个损失函数相加然后一起进行反向传播可能会更加稳定和有效。但在其他情况下,分别计算每个损失函数然后分开进行反向传播可能更合适。要选择合适的方法,需要根据具体情况进行实验和评估。

5.开始训练

训练像往常一样 - 调用训练多次并等待几分钟,打印每个 print_every 示例的当前时间和损失,并存储每个 plot_every 示例的平均损失 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
import time
import math

def timeSince(since):
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)

rnn = RNN(n_letters, 128, n_letters)

n_iters = 100000
print_every = 5000
plot_every = 500
all_losses = []
total_loss = 0 # Reset every ``plot_every`` ``iters``

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

6.对网络进行采样

为了取样,我们给网络一个字母,并询问下一个字母是什么,将其作为下一个字母输入,然后重复直到EOS令牌。

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
max_length = 20

# Sample from a category and starting letter
def sample(category, start_letter='A'):
with torch.no_grad(): # no need to track history in sampling
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

# Get multiple samples from one category and multiple starting letters
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')

tips:

另一种策略是,在训练中加入一个“字符串开头”标记,并让网络选择自己的起始字母,而不是给它一个起始字母。


字符级RNN生成名称!🌞
https://yangchuanzhi20.github.io/2024/02/16/人工智能/Pytorch/项目实战/字符级RNN生成名称/
作者
白色很哇塞
发布于
2024年2月16日
许可协议