Skip to content

Commit ef72d5c

Browse files
committed
ee
ewwe
2 parents bdf8894 + 9c6c089 commit ef72d5c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

106 files changed

+7566
-79
lines changed

.idea/workspace.xml

Lines changed: 215 additions & 69 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

FifthSection/Char RNN Classification.md

Lines changed: 514 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 386 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,386 @@
1+
# 使用字符级RNN生成名字
2+
在上一个[教程](https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html)中,
3+
中我们使用RNN网络对名字所属的语言进行分类。这一次我们会反过来根据语言生成名字。
4+
```buildoutcfg
5+
> python sample.py Russian RUS
6+
Rovakov
7+
Uantov
8+
Shavakov
9+
10+
> python sample.py German GER
11+
Gerren
12+
Ereng
13+
Rosher
14+
15+
> python sample.py Spanish SPA
16+
Salla
17+
Parer
18+
Allan
19+
20+
> python sample.py Chinese CHI
21+
Chan
22+
Hang
23+
Iun
24+
```
25+
我们仍使用只有几层线性层的小型RNN。最大的区别在于,这里不是在读取一个名字的所有字母后预测类别,而是输入一个类别之后在每一时刻
26+
输出一个字母。循环预测字符以形成语言通常也被称为“语言模型”。(也可以将字符换成单词或更高级的结构进行这一过程)
27+
28+
* **阅读建议**
29+
30+
开始本教程前,你已经安装好了PyTorch,并熟悉Python语言,理解“张量”的概念:
31+
32+
* https://pytorch.org/ PyTorch 安装指南
33+
* [Deep Learning with PyTorch:A 60 Minute Blitz ](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html):PyTorch的基本入门教程
34+
* [Learning PyTorch with Examples](https://github.com/fendouai/PyTorchDocs/blob/master/ThirdSection/LearningPyTorch.md):得到深层而广泛的概述
35+
* [PyTorch for Former Torch Users Lua Torch](https://pytorch.org/tutorials/beginner/former_torchies_tutorial.html):如果你曾是一个Lua张量的使用者
36+
37+
事先学习并了解RNN的工作原理对理解这个例子十分有帮助:
38+
39+
* [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/)展示了很多实际的例子
40+
* [Understanding LSTM Networks](https://colah.github.io/posts/2015-08-Understanding-LSTMs/)是关于LSTM的,但也提供有关RNN的说明
41+
42+
## 1.准备数据
43+
点击这里[下载数据](https://download.pytorch.org/tutorial/data.zip)并将其解压到当前文件夹。
44+
45+
有关此过程的更多详细信息,请参阅上一个教程。简而言之,有一些纯文本文件`data/names/[Language].txt`,它们的每行都有一个名字。
46+
我们按行将文本按行分割得到一个数组,将Unicode编码转化为ASCII编码,最终得到`{language: [names ...]}`格式存储的字典变量。
47+
48+
```buildoutcfg
49+
from __future__ import unicode_literals, print_function, division
50+
from io import open
51+
import glob
52+
import os
53+
import unicodedata
54+
import string
55+
56+
all_letters = string.ascii_letters + " .,;'-"
57+
n_letters = len(all_letters) + 1 # Plus EOS marker
58+
59+
def findFiles(path): return glob.glob(path)
60+
61+
# 将Unicode字符串转换为纯ASCII, 感谢https://stackoverflow.com/a/518232/2809427
62+
def unicodeToAscii(s):
63+
return ''.join(
64+
c for c in unicodedata.normalize('NFD', s)
65+
if unicodedata.category(c) != 'Mn'
66+
and c in all_letters
67+
)
68+
69+
# 读取文件并分成几行
70+
def readLines(filename):
71+
lines = open(filename, encoding='utf-8').read().strip().split('\n')
72+
return [unicodeToAscii(line) for line in lines]
73+
74+
# 构建category_lines字典,列表中的每行是一个类别
75+
category_lines = {}
76+
all_categories = []
77+
for filename in findFiles('data/names/*.txt'):
78+
category = os.path.splitext(os.path.basename(filename))[0]
79+
all_categories.append(category)
80+
lines = readLines(filename)
81+
category_lines[category] = lines
82+
83+
n_categories = len(all_categories)
84+
85+
if n_categories == 0:
86+
raise RuntimeError('Data not found. Make sure that you downloaded data '
87+
'from https://download.pytorch.org/tutorial/data.zip and extract it to '
88+
'the current directory.')
89+
90+
print('# categories:', n_categories, all_categories)
91+
print(unicodeToAscii("O'Néàl"))
92+
```
93+
94+
* 输出结果
95+
```buildoutcfg
96+
# categories: 18 ['French', 'Czech', 'Dutch', 'Polish', 'Scottish', 'Chinese', 'English', 'Italian', 'Portuguese', 'Japanese', 'German', 'Russian', 'Korean', 'Arabic', 'Greek', 'Vietnamese', 'Spanish', 'Irish']
97+
O'Neal
98+
```
99+
100+
## 2.构造神经网络
101+
这个神经网络比[上一个RNN教程](https://github.com/apachecn/pytorch-doc-zh/blob/master/docs/1.0/char_rnn_generation_tutorial.md#Creating-the-Network)
102+
中的网络增加了额外的类别张量参数,该参数与其他输入连接在一起。类别可以像字母一样组成 one-hot 向量构成张量输入。
103+
104+
我们将输出作为下一个字母是什么的可能性。采样过程中,当前输出可能性最高的字母作为下一时刻输入字母。
105+
106+
在组合隐藏状态和输出之后我们增加了第二个linear层`o2o`,使模型的性能更好。当然还有一个dropout层,参考这篇论文[随机将输入部分替换为0](https://arxiv.org/abs/1207.0580)
107+
给出的参数(dropout=0.1)来模糊处理输入防止过拟合。
108+
我们将它添加到网络的末端,故意添加一些混乱使采样特征增加。
109+
```buildoutcfg
110+
import torch
111+
import torch.nn as nn
112+
113+
class RNN(nn.Module):
114+
def __init__(self, input_size, hidden_size, output_size):
115+
super(RNN, self).__init__()
116+
self.hidden_size = hidden_size
117+
118+
self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
119+
self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
120+
self.o2o = nn.Linear(hidden_size + output_size, output_size)
121+
self.dropout = nn.Dropout(0.1)
122+
self.softmax = nn.LogSoftmax(dim=1)
123+
124+
def forward(self, category, input, hidden):
125+
input_combined = torch.cat((category, input, hidden), 1)
126+
hidden = self.i2h(input_combined)
127+
output = self.i2o(input_combined)
128+
output_combined = torch.cat((hidden, output), 1)
129+
output = self.o2o(output_combined)
130+
output = self.dropout(output)
131+
output = self.softmax(output)
132+
return output, hidden
133+
134+
def initHidden(self):
135+
return torch.zeros(1, self.hidden_size)
136+
```
137+
138+
## 3.训练
139+
#### 3.1 训练准备
140+
首先,构造一个可以随机获取成对训练数据(category, line)的函数。
141+
```buildoutcfg
142+
import random
143+
144+
# 列表中的随机项
145+
def randomChoice(l):
146+
return l[random.randint(0, len(l) - 1)]
147+
148+
# 从该类别中获取随机类别和随机行
149+
def randomTrainingPair():
150+
category = randomChoice(all_categories)
151+
line = randomChoice(category_lines[category])
152+
return category, line
153+
```
154+
155+
对于每个时间步长(即,对于要训练单词中的每个字母),网络的输入将是“`(类别,当前字母,隐藏状态)`”,输出将是“`(下一个字母,
156+
下一个隐藏状态)`”。因此,对于每个训练集,我们将需要类别、一组输入字母和一组输出/目标字母。
157+
158+
在每一个时间序列,我们使用当前字母预测下一个字母,所以训练用的字母对来自于一个单词。例如 对于 "`ABCD<EOS>`",我们将创建
159+
(“A”,“B”),(“B”,“C”),(“C”,“D”),(“D”,“EOS”))。
160+
161+
类别张量是一个`<1 x n_categories>`尺寸的[one-hot张量](https://en.wikipedia.org/wiki/One-hot)。训练时,我们在每一个时间序
162+
列都将其提供给神经网络。这是一种选择策略,也可选择将其作为初始隐藏状态的一部分,或者其他什么结构。
163+
```buildoutcfg
164+
# 类别的One-hot张量
165+
def categoryTensor(category):
166+
li = all_categories.index(category)
167+
tensor = torch.zeros(1, n_categories)
168+
tensor[0][li] = 1
169+
return tensor
170+
171+
# 用于输入的从头到尾字母(不包括EOS)的one-hot矩阵
172+
def inputTensor(line):
173+
tensor = torch.zeros(len(line), 1, n_letters)
174+
for li in range(len(line)):
175+
letter = line[li]
176+
tensor[li][0][all_letters.find(letter)] = 1
177+
return tensor
178+
179+
# 用于目标的第二个结束字母(EOS)的LongTensor
180+
def targetTensor(line):
181+
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
182+
letter_indexes.append(n_letters - 1) # EOS
183+
return torch.LongTensor(letter_indexes)
184+
```
185+
186+
为了方便训练,我们将创建一个`randomTrainingExample`函数,该函数随机获取(类别,行)的对并将它们转换为所需要的(类别,输入,
187+
目标)格式张量。
188+
```buildoutcfg
189+
# 从随机(类别,行)对中创建类别,输入和目标张量
190+
def randomTrainingExample():
191+
category, line = randomTrainingPair()
192+
category_tensor = categoryTensor(category)
193+
input_line_tensor = inputTensor(line)
194+
target_line_tensor = targetTensor(line)
195+
return category_tensor, input_line_tensor, target_line_tensor
196+
```
197+
198+
#### 3.2 训练神经网络
199+
和只使用最后一个时刻输出的分类任务相比,这次我们每一个时间序列都会进行一次预测,所以每一个时间序列我们都会计算损失。
200+
201+
autograd 的神奇之处在于您可以在每一步中简单地累加这些损失,并在最后反向传播。
202+
```buildoutcfg
203+
criterion = nn.NLLLoss()
204+
205+
learning_rate = 0.0005
206+
207+
def train(category_tensor, input_line_tensor, target_line_tensor):
208+
target_line_tensor.unsqueeze_(-1)
209+
hidden = rnn.initHidden()
210+
211+
rnn.zero_grad()
212+
213+
loss = 0
214+
215+
for i in range(input_line_tensor.size(0)):
216+
output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
217+
l = criterion(output, target_line_tensor[i])
218+
loss += l
219+
220+
loss.backward()
221+
222+
for p in rnn.parameters():
223+
p.data.add_(-learning_rate, p.grad.data)
224+
225+
return output, loss.item() / input_line_tensor.size(0)
226+
```
227+
228+
为了跟踪训练耗费的时间,我添加一个`timeSince(timestamp)`函数,它返回一个人类可读的字符串:
229+
230+
```buildoutcfg
231+
import time
232+
import math
233+
234+
def timeSince(since):
235+
now = time.time()
236+
s = now - since
237+
m = math.floor(s / 60)
238+
s -= m * 60
239+
return '%dm %ds' % (m, s)
240+
```
241+
242+
训练过程和平时一样。多次运行训练,等待几分钟,每`print_every`次打印当前时间和损失。在`all_losses`中保留每`plot_every`次的平
243+
均损失,以便稍后进行绘图。
244+
245+
```buildoutcfg
246+
rnn = RNN(n_letters, 128, n_letters)
247+
248+
n_iters = 100000
249+
print_every = 5000
250+
plot_every = 500
251+
all_losses = []
252+
total_loss = 0 # Reset every plot_every iters
253+
254+
start = time.time()
255+
256+
for iter in range(1, n_iters + 1):
257+
output, loss = train(*randomTrainingExample())
258+
total_loss += loss
259+
260+
if iter % print_every == 0:
261+
print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))
262+
263+
if iter % plot_every == 0:
264+
all_losses.append(total_loss / plot_every)
265+
total_loss = 0
266+
```
267+
268+
* 输出结果:
269+
270+
```buildoutcfg
271+
0m 23s (5000 5%) 3.1569
272+
0m 43s (10000 10%) 2.3132
273+
1m 3s (15000 15%) 2.5069
274+
1m 24s (20000 20%) 1.3100
275+
1m 44s (25000 25%) 3.6083
276+
2m 4s (30000 30%) 3.5398
277+
2m 24s (35000 35%) 2.4387
278+
2m 44s (40000 40%) 2.2262
279+
3m 4s (45000 45%) 2.6500
280+
3m 24s (50000 50%) 2.4559
281+
3m 44s (55000 55%) 2.5030
282+
4m 4s (60000 60%) 2.9417
283+
4m 24s (65000 65%) 2.1571
284+
4m 44s (70000 70%) 1.7415
285+
5m 4s (75000 75%) 2.3649
286+
5m 24s (80000 80%) 3.0096
287+
5m 44s (85000 85%) 1.9196
288+
6m 4s (90000 90%) 1.9468
289+
6m 25s (95000 95%) 2.1522
290+
6m 45s (100000 100%) 2.0344
291+
```
292+
293+
#### 3.3 损失数据作图
294+
`all_losses`得到历史损失记录,反映了神经网络的学习情况:
295+
296+
```buildoutcfg
297+
import matplotlib.pyplot as plt
298+
import matplotlib.ticker as ticker
299+
300+
plt.figure()
301+
plt.plot(all_losses)
302+
```
303+
304+
![](https://pytorch.org/tutorials/_images/sphx_glr_char_rnn_generation_tutorial_001.png)
305+
306+
## 4.网络采样
307+
我们每次给网络提供一个字母并预测下一个字母是什么,将预测到的字母继续输入,直到得到EOS字符结束循环。
308+
309+
* 用输入类别、起始字母和空隐藏状态创建输入张量。
310+
311+
* 用起始字母构建一个字符串变量 output_name
312+
313+
* 得到最大输出长度,<br/>
314+
&emsp; * 将当前字母传入神经网络<br/>
315+
&emsp; * 从前一层得到下一个字母和下一个隐藏状态<br/>
316+
&emsp; * 如果字母是EOS,在这里停止<br/>
317+
&emsp; * 如果是一个普通的字母,添加到output_name变量并继续循环<br/>
318+
* 返回最终得到的名字单词<br/>
319+
320+
另一种策略是,不必给网络一个起始字母,而是在训练中提供一个“字符串开始”的标记,并让网络自己选择起始的字母。
321+
322+
```buildoutcfg
323+
max_length = 20
324+
325+
# 来自类别和首字母的样本
326+
def sample(category, start_letter='A'):
327+
with torch.no_grad(): # no need to track history in sampling
328+
category_tensor = categoryTensor(category)
329+
input = inputTensor(start_letter)
330+
hidden = rnn.initHidden()
331+
332+
output_name = start_letter
333+
334+
for i in range(max_length):
335+
output, hidden = rnn(category_tensor, input[0], hidden)
336+
topv, topi = output.topk(1)
337+
topi = topi[0][0]
338+
if topi == n_letters - 1:
339+
break
340+
else:
341+
letter = all_letters[topi]
342+
output_name += letter
343+
input = inputTensor(letter)
344+
345+
return output_name
346+
347+
# 从一个类别和多个起始字母中获取多个样本
348+
def samples(category, start_letters='ABC'):
349+
for start_letter in start_letters:
350+
print(sample(category, start_letter))
351+
352+
samples('Russian', 'RUS')
353+
354+
samples('German', 'GER')
355+
356+
samples('Spanish', 'SPA')
357+
358+
samples('Chinese', 'CHI')
359+
```
360+
361+
* 输出结果:
362+
363+
```buildoutcfg
364+
Rovanik
365+
Uakilovev
366+
Shaveri
367+
Garter
368+
Eren
369+
Romer
370+
Santa
371+
Parera
372+
Artera
373+
Chan
374+
Ha
375+
Iua
376+
```
377+
378+
## 练习
379+
* 尝试其它 (类别->行) 格式的数据集,比如:<br/>
380+
&emsp; * 系列小说 -> 角色名称<br/>
381+
&emsp; * 词性 -> 单词<br/>
382+
&emsp; * 国家 -> 城市<br/>
383+
* 尝试“start of sentence” 标记,使采样的开始过程不需要指定起始字母<br/>
384+
* 通过更大和更复杂的网络获得更好的结果<br/>
385+
&emsp; * 尝试 nn.LSTM 和 nn.GRU 层<br/>
386+
&emsp; * 组合这些 RNN构造更复杂的神经网络<br/>

0 commit comments

Comments
 (0)