第四课 文本预处理
文本是一类序列数据,一篇文章可以看作是字符或单词的序列。用神经网络处理文本时会存在一个问题,文本实际上是字符串,但神经网络是做数值处理,无法直接作用于字符串,因此,我们需要对文本进行预处理。
接下来介绍一些基础的步骤。
读入文本
用H.G.Well的Time Machine作为示例。
import collections
import re
def read_time_machine():
with open('<your-path>/timemachine.txt','r') as f:
# 这条语句就是将文本每一行全部转化为小写
# 且将非小写字母的其他字符全部用空格代替
lines = [re.sub('[^a-z]+','',line.strip().lower()) for line in f:]
return lines
lines = read_time_machine() # type is list
print('# sentences %d' % len(lines))
output:
# sentences 3221
- collections模块:数据结构常用模块,常用类型有:计数器(Counter)、双向队列(deque)、默认字典(defaultdict)、有序字典(OrderedDict)、可命名元组(namedtuple)。Counter对访问对象进行计数并返回一个字典,具体可参考OneMore
- re模块:python独有的匹配字符串的模块,多基于正则表达式实现,具体可参考Brigth-Python之re模块
- open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)函数用于打开文件并进行相应处理,可用的模式有很多,这里介绍几个常见的:
‘r’——以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
’r+‘——打开一个文件用于读写。文件指针将会放在文件的开头。
’w‘——打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
‘w+’——打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 - re.sub(pattern,repl,string,count = 0,flags = 0 ):pattern是字符的模式,repl用于替换字符串中对应pattern的对象,它可以时函数,也可以是字符串,string即要替换的字符串序列,count表示替换的次数。
import re
# 将查找到的数字替换成AA,替换2次
x = re.sub('\d', 'AA', 'fhd638dnhs687f', 2)
# 默认全部替换
y = re.sub('\d', 'AA', 'fhd638dnhs687f')
print(x)
print(y)
output:
'fhdAAAA8dnhs687f'
'fhdAAAAAAdnhsAAAAAAf'
- [a-z]——表示从a到z所有小写字母的字符组,[^…]——表示除了字符组中字符的所有其他字符,+——表示重复一次或多次。因此[^a-z]+表示除了所有小写字母以外的字符,这些其他字符重复一次或多次全都计算在内。
- strip()方法:str.strip()用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
- lower() 方法:str.lower()转换字符串中所有大写字符为小写。
分词
我们对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。
def tokenize(sentences, token='word'):
"""Split sentences into word or char tokens"""
# 做单词级别的分词
if token == 'word':
return [sentence.split(' ') for sentence in sentences]
# 做字符级别的分词
elif token == 'char':
return [list(sentence) for sentence in sentences]
else:
print('ERROR: unkown token type '+token)
# 返回一个二维列表,第一个维度是sentences中每个句子,
# 第二个维度是每个句子分词之后得到的单词或序列
tokens = tokenize(lines)
tokens[0:2]
output:
[['the', 'time', 'machine', 'by', 'h', 'g', 'wells', ''], ['']]
建立字典
为了方便模型处理,我们需要将字符串转换为数字。因此我们需要先构建一个字典(vocabulary),将每个词映射到一个唯一的索引编号。
class Vocab(object):
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
'''
tokens是一个二维列表,包含所有语句的词
min_freq设定一个词出现的最低频数,小于这个频数的词就忽略
use_special_tokens是否使用特殊的词
'''
# 进行去重与统计词频
counter = count_corpus(tokens) #
self.token_freqs = list(counter.items())
# print(self.token_freqs[0:2])
# output: [('the', 2261), ('time', 200)]
self.idx_to_token = []
if use_special_tokens:
# padding, begin of sentence, end of sentence, unknown
# self.pad:神经网络批量处理句子时以矩阵方式输入,每一行为一个句子,句子长短不一,因此padding
# self.bos:在句子首尾加上特殊字符,表明句子的开始和结束
# self.unk:语料库中没有出现过的词
self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
self.idx_to_token += ['', '', '', '']
else:
self.unk = 0
self.idx_to_token += ['']
self.idx_to_token += [token for token, freq in self.token_freqs
if freq >= min_freq and token not in self.idx_to_token]
# ind_to_token是包含了所有词的列表
# token_to_inx是一个字典:{'字符':下标}
self.token_to_idx = dict()
for idx, token in enumerate(self.idx_to_token):
self.token_to_idx[token] = idx
def __len__(self):
return len(self.idx_to_token)
def __getitem__(self, tokens):
if not isinstance(tokens, (list, tuple)):
return self.token_to_idx.get(tokens, self.unk)
return [self.__getitem__(token) for token in tokens]
# 根据下标返回token
def to_tokens(self, indices):
if not isinstance(indices, (list, tuple)):
return self.idx_to_token[indices]
return [self.idx_to_token[index] for index in indices]
def count_corpus(sentences):
tokens = [tk for st in sentences for tk in st]
return collections.Counter(tokens) # 返回一个字典,记录每个词的出现次数
vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])
print(vocab.to_tokens([18,20]))
output:
[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9)]
['of', 'was']
将词转化为索引
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])
output:
words: ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him', '']
indices: [1, 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
words: ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
indices: [20, 21, 22, 23, 24, 16, 25, 26, 27, 28, 29, 30]
现有工具进行分词
上述分词方法简单且存在缺陷:
- 标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了
- 类似“shouldn’t", "doesn’t"这样的词会被错误地处理
- 类似"Mr.", "Dr."这样的词会被错误地处理
处理文本分词的工具包:是spaCy和NLTK
例子:
sapCy:
import spacy
text = "Mr. Chen doesn't agree with my suggestion."
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
output:
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
NLTK:
from nltk.tokenize import word_tokenize
from nltk import data
text = "Mr. Chen doesn't agree with my suggestion."
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
output:
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
第五课 语言模型
什么是语言模型?给定一个长度为
T
T
T的词的序列
x
1
,
x
2
,
⋯
,
x
T
x_1,x_2,\cdots,x_T
x1,x2,⋯,xT,语言模型的目标就是就是评估改序列是否合理,即计算序列的概率:
P
(
x
1
,
x
2
,
⋯
,
x
T
)
.
P(x_1,x_2,\cdots,x_T).
P(x1,x2,⋯,xT).
概率越大,合理性越高。本节课介绍基于统计的语言模型,主要是 n n n元语法(n-gram)。
假设序列
x
1
,
x
2
,
⋯
,
x
T
x_1,x_2,\cdots,x_T
x1,x2,⋯,xT中每个词是依次生成的,那么序列生成的概率为
P
(
x
1
,
x
2
,
⋯
,
x
T
)
=
∏
t
=
1
T
P
(
x
t
∣
x
1
,
⋯
,
x
t
−
1
)
P(x_1,x_2,\cdots,x_T)=\prod_{t=1}^TP(x_t|x_1,\cdots,x_{t-1})
P(x1,x2,⋯,xT)=t=1∏TP(xt∣x1,⋯,xt−1)
第一项表示
x
1
x_1
x1这个词出现的概率,后面的项表示在前面出现
x
1
,
⋯
,
x
i
x_1,\cdots,x_i
x1,⋯,xi这些词的情况下,下一项出现
x
i
+
1
x_{i+1}
xi+1的可能性,因此为条件概率。
词的概率可以通过该词在训练数据集中的相对词频来计算,例如,
x
1
x_1
x1的概率可以计算为:
P
^
(
x
1
)
=
n
(
x
1
)
n
\hat{P}(x_1)=\frac{n(x_1)}{n}
P^(x1)=nn(x1)
其中 n ( x 1 ) n(x_1) n(x1)为语料库中以 x 1 x_1 x1作为第一个词的文本数量, n n n为语料库中文本总数。
条件概率的计算公式为(以
x
1
x_1
x1为例):
P
^
(
x
2
∣
x
1
)
=
n
(
x
1
,
x
2
)
n
(
x
1
)
.
\hat{P}(x_2|x_1)=\frac{n(x_1,x_2)}{n(x_1)}.
P^(x2∣x1)=n(x1)n(x1,x2).
n元语法
序列长度增加,计算和存储多个词共同出现的概率的复杂度会呈指数级增加。因此这里提出了马尔可夫链的概念,假设后一个词的出现只与前 n n n个词相关,称为 n n n阶马尔科夫链。基于 n − 1 n-1 n−1阶马尔科夫链的概率语言模型也叫 n n n元语法。当n较小时,n元语法往往并不准确。例如,在一元语法中,由三个词组成的句子“你走先”和“你先走”的概率是一样的。然而,当n较大时,n元语法需要计算并存储大量的词频和多词相邻频率。
n元语法的缺陷:
- 参数空间过大。例如字典大小为 V V V,序列长度为 T T T,那么需要计算的参数为 V + V 2 + V 3 V+V^2+V^3 V+V2+V3。
- 数据稀疏。齐夫定律说明大部分词的词频很小,甚至不会在语料库里出现,因此对这些词概率的估计都不准确,而且频率较高的词通常是一些连接词,这些词会有大量的组合,但这些组合根本不会出现,因此都是0,从而使得数据稀疏。齐夫定律:在自然语言的语料库里,一个单词出现的频率与它在频率表里的排名成反比。
语言模型数据集
读取数据集
# 读取数据,输出长度和前40个字符
with open('/home/kesci/input/jaychou_lyrics4703/jaychou_lyrics.txt') as f:
corpus_chars = f.read()
print(len(corpus_chars))
print(corpus_chars[: 40])
# 将换行符和回车符全部用空格代替
corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')
# 只取前10000个字符
corpus_chars = corpus_chars[: 10000]
output:
63282
想要有直升机
想要和你飞到宇宙去
想要和你融化在一起
融化在宇宙里
我每天每天每
建立字符索引
# set去重,得到索引到字符的映射
idx_to_char = list(set(corpus_chars))
char_to_idx = {char: i for i, char in enumerate(idx_to_char)} # 字符到索引的映射
vocab_size = len(char_to_idx)
print(vocab_size)
corpus_indices = [char_to_idx[char] for char in corpus_chars] # 将每个字符转化为索引,得到一个索引的序列
sample = corpus_indices[: 20]
# join()函数,这里以空格作为分隔符
print('chars:', ''.join([idx_to_char[idx] for idx in sample]))
print('indices:', sample)
- set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
x = set('runoob')
y = set('google')
print(x)
print(y)
print(x & y) # 交集
print(x | y) # 并集
print(x - y) # 差集
output:
{'b', 'r', 'u', 'o', 'n'}
{'e', 'o', 'g', 'l'}
{'o'}
{'l', 'b', 'r', 'u', 'g', 'e', 'o', 'n'}
{'b', 'u', 'n', 'r'}
- join()函数:连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串。
a = 'You are my friend'
b = ''.join(a)
c = '-'.join(a)
print(b)
print(c)
output:
You are my friend
Y-o-u- -a-r-e- -m-y- -f-r-i-e-n-d
时序数据的采样
在训练中我们需要每次随机读取小批量样本和标签。与之前章节的实验数据不同的是,时序数据的一个样本通常包含连续的字符。假设时间步数为5,样本序列为5个字符,即“想”“要”“有”“直”“升”。该样本的标签序列为这些字符分别在训练集中的下一个字符,即“要”“有”“直”“升”“机”,即 X X X =“想要有直升”, Y Y Y =“要有直升机”。
如果序列的长度为 T T T ,时间步数为 n n n ,那么一共有 T − n T−n T−n 个合法的样本,但是这些样本有大量的重合,我们通常采用更加高效的采样方式。我们有两种方式对时序数据进行采样,分别是随机采样和相邻采样。
随机采样
下面的代码每次从数据里随机采样一个小批量。其中批量大小batch_size是每个小批量的样本数,num_steps是每个样本所包含的时间步数。 在随机采样中,每个样本是原始序列上任意截取的一段序列,相邻的两个随机小批量在原始序列上的位置不一定相毗邻。
随机采样示意图:
代码展示:
import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
# 减1是因为对于长度为n的序列,X最多只有包含其中的前n - 1个字符
num_examples = (len(corpus_indices) - 1) // num_steps # 下取整,得到不重叠情况下的样本个数
example_indices = [i * num_steps for i in range(num_examples)] # 每个样本的第一个字符在corpus_indices中的下标
random.shuffle(example_indices)
def _data(i):
# 返回从i开始的长为num_steps的序列
return corpus_indices[i: i + num_steps]
if device is None:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
for i in range(0, num_examples, batch_size):
# 每次选出batch_size个随机样本
batch_indices = example_indices[i: i + batch_size] # 当前batch的各个样本的首字符的下标
X = [_data(j) for j in batch_indices]
Y = [_data(j + 1) for j in batch_indices]
yield torch.tensor(X, device=device), torch.tensor(Y, device=device)
my_seq = list(range(30))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=6):
print('X: ', X, '\nY:', Y, '\n')
output:
X: tensor([[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]])
X: tensor([[ 0, 1, 2, 3, 4, 5],
[18, 19, 20, 21, 22, 23]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[19, 20, 21, 22, 23, 24]])
神经网络输入都是文本字符在语料库中的索引。
相邻采样
在相邻采样中,相邻的两个随机小批量在原始序列上的位置相毗邻。
相邻采样示例:
代码展示:
ef data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None):
if device is None:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
corpus_len = len(corpus_indices) // batch_size * batch_size # 保留下来的序列的长度
corpus_indices = corpus_indices[: corpus_len] # 仅保留前corpus_len个字符
indices = torch.tensor(corpus_indices, device=device)
indices = indices.view(batch_size, -1) # resize成(batch_size, )
# 这里的操作类似随机采样
batch_num = (indices.shape[1] - 1) // num_steps
for i in range(batch_num):
i = i * num_steps
X = indices[:, i: i + num_steps]
Y = indices[:, i + 1: i + num_steps + 1]
yield X, Y
for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=6):
print('X: ', X, '\nY:', Y, '\n')
output:
X: tensor([[ 0, 1, 2, 3, 4, 5],
[15, 16, 17, 18, 19, 20]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[16, 17, 18, 19, 20, 21]])
X: tensor([[ 6, 7, 8, 9, 10, 11],
[21, 22, 23, 24, 25, 26]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[22, 23, 24, 25, 26, 27]])
第六课 循环神经网络基础
以循环神经网络实现语言模型为例。
下面分析构造。假设
X
t
∈
R
n
×
d
X_t\in\mathbb{R}^{n\times d}
Xt∈Rn×d是时间步
t
t
t的小批量输入,
H
t
∈
R
n
×
h
H_t\in\mathbb{R}^{n\times h}
Ht∈Rn×h是该时间步的隐藏变量,则
H
t
=
Φ
(
X
t
W
x
h
+
H
t
−
1
W
h
h
+
b
h
)
.
H_t = \Phi(X_tW_{xh}+H_{t-1}W_{hh}+b_h).
Ht=Φ(XtWxh+Ht−1Whh+bh).
对于每一个字符和每一个隐藏变量都用一个向量来表示,这里的
d
d
d和
h
h
h分别表示两个向量的长度。
W
x
h
∈
d
×
h
,
W
h
h
∈
R
h
×
h
,
b
∈
R
1
×
h
W_{xh}\in\mathbb{d\times h}, W_{hh}\in\mathbb{R}^{h\times h},b\in\mathbb{R}^{1\times h}
Wxh∈d×h,Whh∈Rh×h,b∈R1×h,由此知
X
t
W
x
h
∈
R
n
×
h
,
H
t
−
1
W
h
h
∈
R
n
×
h
X_tW_{xh}\in\mathbb{R}^{n\times h}, H_{t-1}W_{hh}\in\mathbb{R}^{n\times h}
XtWxh∈Rn×h,Ht−1Whh∈Rn×h,根据加法的广播机制,三项相加结果为
n
×
h
n\times h
n×h的矩阵。
Φ
\Phi
Φ是非线性激活函数。
在时间步
t
t
t,输出层的输出为:
O
t
=
H
t
W
h
q
+
b
q
.
O_t=H_tW_{hq}+b_q.
Ot=HtWhq+bq.
one-hot向量
我们需要将字符表示成向量,这里采用one-hot向量。假设词典大小是 N N N,每次字符对应一个从0到 N − 1 N−1 N−1的唯一的索引,则该字符的向量是一个长度为 N N N 的向量,若字符的索引是 $i , 则 该 向 量 的 第 ,则该向量的第 ,则该向量的第 i $个位置为 1 ,其他位置为 0 。下面分别展示了索引为0和2的one-hot向量,向量长度等于词典大小。
def one_hot(x, n_class, dtype=torch.float32):
# x是一个一维的向量,每个元素都是一个字符的索引
# n_class是字典的大小,vocab_size
# dtype为返回向量的数值类型,size为(n,n_class)
result = torch.zeros(x.shape[0], n_class, dtype=dtype, device=x.device) # shape: (n, n_class)
result.scatter_(1, x.long().view(-1, 1), 1) # result[i, x[i, 0]] = 1
return result
- scatter_()函数
我们每次采样的小批量的形状是(批量大小, 时间步数)。下面的函数将这样的小批量变换成数个形状为(批量大小, 词典大小)的矩阵,矩阵个数等于时间步数。也就是说,时间步 t t t的输入为 X t ∈ R n × d X_t\in\mathbb{R}^{n×d } Xt∈Rn×d,其中 n n n 为批量大小, d d d 为词向量大小,即one-hot向量长度(词典大小)。
def to_onehot(X, n_class):
# X: 一个小批量
# 输出为(批量大小, 词典大小)
return [one_hot(X[:, i], n_class) for i in range(X.shape[1])]
定义模型
函数rnn用循环的方式依次完成循环神经网络每个时间步的计算。
def rnn(inputs, state, params):
# inputs是长度为num_steps的列表,每个元素是(batch_size, vocab_size)的矩阵
# state提供状态的初始值,是一个元组,在rnn中就是隐藏状态
# inputs和outputs皆为num_steps个形状为(batch_size, vocab_size)的矩阵
W_xh, W_hh, b_h, W_hq, b_q = params
H, = state # rnn中只有一个状态要维护,就是隐藏状态
outputs = []
for X in inputs:
H = torch.tanh(torch.matmul(X, W_xh) + torch.matmul(H, W_hh) + b_h)
Y = torch.matmul(H, W_hq) + b_q
outputs.append(Y)
return outputs, (H,)
# 返回h是因为后面要用相邻采样进行训练,对于相邻采样而言,当前这个batch的最后状态就作为下一个状态的初始值
- X.to(device)
裁剪梯度
循环神经网络中较容易出现梯度衰减或梯度爆炸,这是因为梯度的传播方式是通过时间反向传播,梯度是幂的形式,指数就是num_steps,随着时间步数增加,就容易出现这些问题。裁剪梯度(clip gradient)是一种应对梯度爆炸的方法。假设我们把所有模型参数的梯度拼接成一个向量 g ,并设裁剪的阈值是 θ 。裁剪后的梯度
min
(
θ
∣
∣
g
∣
∣
,
1
)
g
\min(\frac{\theta}{||g||},1)g
min(∣∣g∣∣θ,1)g
的
L
2
L_2
L2范数不超过
θ
\theta
θ。
代码展示:
def grad_clipping(params, theta, device):
norm = torch.tensor([0.0], device=device)
for param in params:
norm += (param.grad.data ** 2).sum()
norm = norm.sqrt().item()
if norm > theta:
for param in params:
param.grad.data *= (theta / norm)
定义预测函数
以下函数基于前缀prefix(含有数个字符的字符串)来预测接下来的num_chars个字符。
代码展示:
def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,
num_hiddens, vocab_size, device, idx_to_char, char_to_idx):
state = init_rnn_state(1, num_hiddens, device)
output = [char_to_idx[prefix[0]]] # output记录prefix加上预测的num_chars个字符
for t in range(num_chars + len(prefix) - 1):
# 将上一时间步的输出作为当前时间步的输入
# 这里的batch_size为1
X = to_onehot(torch.tensor([[output[-1]]], device=device), vocab_size)
# 计算输出和更新隐藏状态
(Y, state) = rnn(X, state, params)
# 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符
if t < len(prefix) - 1:
output.append(char_to_idx[prefix[t + 1]])
else:
output.append(Y[0].argmax(dim=1).item()) # 这里用Y[0]是因为Y输出的是一个列表,取出Y中第一个元素
return ''.join([idx_to_char[i] for i in output])
torch.flatten()函数(转自GhostintheCode,这个博主介绍的很详细,可进去看看例子):
#展平一个连续范围的维度,输出类型为Tensor
torch.flatten(input, start_dim=0, end_dim=-1) → Tensor
#Parameters:input (Tensor) – 输入为Tensor
#start_dim (int) – 展平的开始维度
#end_dim (int) – 展平的最后维度
#一个3x2x2的三维张量
>>> t = torch.tensor([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]],
[[9, 10],
[11, 12]]])
#当开始维度为0,最后维度为-1,展开为一维
>>> torch.flatten(t)
tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
#当开始维度为0,最后维度为-1,展开为3x4,也就是说第一维度不变,后面的压缩
>>> torch.flatten(t, start_dim=1)
tensor([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
————————————————
版权声明:本文为优快云博主「GhostintheCode」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/GhostintheCode/article/details/102530451
循环神经网络的简洁实现
我们使用Pytorch中的nn.RNN来构造循环神经网络。在本节中,我们主要关注nn.RNN的以下几个构造函数参数:
- input_size - The number of expected features in the input x (整型,int)
- hidden_size – The number of features in the hidden state h(整型,int)
- nonlinearity – The non-linearity to use. Can be either ‘tanh’ or ‘relu’. Default: ‘tanh’
- batch_first – If True, then the input and output tensors are provided as (batch_size, num_steps, input_size). Default: False
这里的batch_first决定了输入的形状,我们使用默认的参数False,对应的输入形状是 (num_steps, batch_size, input_size)。
一个完整的基于循环神经网络的语言模型
class RNNModel(nn.Module):
def __init__(self, rnn_layer, vocab_size):
super(RNNModel, self).__init__()
self.rnn = rnn_layer
# 这里取1
self.hidden_size = rnn_layer.hidden_size * (2 if rnn_layer.bidirectional else 1)
self.vocab_size = vocab_size
self.dense = nn.Linear(self.hidden_size, vocab_size)
def forward(self, inputs, state):
# inputs.shape: (batch_size, num_steps)
X = to_onehot(inputs, vocab_size)
X = torch.stack(X) # X.shape: (num_steps, batch_size, vocab_size)
hiddens, state = self.rnn(X, state)
hiddens = hiddens.view(-1, hiddens.shape[-1]) # hiddens.shape: (num_steps * batch_size, hidden_size)
output = self.dense(hiddens)
return output, state