我的博客

pytorch 官网教程 - 字符级别 RNN 实现不同语言的名字的生成

目录
  1. 加载数据
    1. 统一为 ascii 字母
    2. 读文件
  2. 定义网络
  3. 训练模型
    1. 随机选择数据
    2. 向量化
  4. 训练

有关数据的介绍参见 pytorch 官网教程 - 字符级别 RNN 实现姓名分类

本文参考 pytorch 官网教程

加载数据

统一为 ascii 字母

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
import glob
import string
import unicodedata

all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)

def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
and c in all_letters
)

读文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
category_lines = {}
all_categories = []

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

for filename in glob.glob('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)

定义网络

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)

训练模型

随机选择数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

# 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

向量化

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)

训练

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 = 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_(-learning_rate, p.grad.data)

return output, loss.item() / input_line_tensor.size(0)
1
2
3
4
5
6
7
8
9
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0m 42s (5000 5%) 2.5946
1m 27s (10000 10%) 3.2678
2m 11s (15000 15%) 2.8750
2m 55s (20000 20%) 2.1062
3m 39s (25000 25%) 2.6433
4m 22s (30000 30%) 2.4880
5m 3s (35000 35%) 1.7367
5m 44s (40000 40%) 2.5925
6m 28s (45000 45%) 3.2732
7m 11s (50000 50%) 2.1813
7m 54s (55000 55%) 2.3359
8m 36s (60000 60%) 2.2754
9m 19s (65000 65%) 3.6193
10m 1s (70000 70%) 2.1370
10m 45s (75000 75%) 1.8560
11m 28s (80000 80%) 2.1922
12m 10s (85000 85%) 2.0933
12m 53s (90000 90%) 2.3829
13m 35s (95000 95%) 2.2680
14m 17s (100000 100%) 1.8874

绘图 loss 变化

1
2
3
4
5
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)

评论无需登录,可以匿名,欢迎评论!