此二者的本质都是对rnn进行改良:关注当前多还是关注之前多。
在此详细讲一下。
目录
1.GRU门循环控制单元
1.1理论:
1.2初始化参数
1.3定义网络
1.4训练命令行
1.5简洁实现
2.Lstm长短期记忆网络
2.1理论
2.2加载参数
2.3定义lstm计算
2.4定义模型:
2.5训练命令行
3.强调
其参数多了两个,本质都是对H的计算进行了改进。
与从零开始RNN的初始化参数类似,首先指定输入输出维度=len(vocab)
构建一个均值=0,std=0.01的初始化tensor,传入的是尺寸
将更新门、重置门、候选隐状态的参数都是3个,构造初始化辅助函数three,直接赋值即可得到相应的初始化参数(初始化需要的参数形式相同,故一样)
传入的X尺寸为(bs,V),系数W的尺寸为(V,h)/(h,V),H的尺寸为(bs,h);与X或H相乘得到(bs,V),这其实就是Y的尺寸,再相应dim=0上叠加,得到最终一个T的outputs为(bs*T,V)
def get_params(vocab_size, num_hiddens, device):
num_inputs = num_outputs = vocab_size
def normal(shape):
return torch.randn(size=shape, device=device)*0.01
def three():
return (normal((num_inputs, num_hiddens)),
normal((num_hiddens, num_hiddens)),
torch.zeros(num_hiddens, device=device))
W_xz, W_hz, b_z = three() # 更新⻔参数
W_xr, W_hr, b_r = three() # 重置⻔参数
W_xh, W_hh, b_h = three() # 候选隐状态参数
# 输出层参数
W_hq = normal((num_hiddens, num_outputs))
b_q = torch.zeros(num_outputs, device=device)
# 附加梯度
params = [W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q]
for param in params:
param.requires_grad_(True)
return params
初始化参数:
def init_gru_state(batch_size, num_hiddens, device):
return (torch.zeros((batch_size, num_hiddens), device=device), )
定义gru计算:
注意: @这个符号是矩阵乘法,*是哈达玛积
H的尺寸仍是(bs,h),注意W_hz;W_hr等的尺寸为(h,h)
计算公式与开始的理论图里面的公式一致。
def gru(inputs, state, params):
W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q = params
H, = state
outputs = []
for X in inputs:
Z = torch.sigmoid((X @ W_xz) + (H @ W_hz) + b_z)
R = torch.sigmoid((X @ W_xr) + (H @ W_hr) + b_r)
H_tilda = torch.tanh((X @ W_xh) + ((R * H) @ W_hh) + b_h)
H = Z * H + (1 - Z) * H_tilda
Y = H @ W_hq + b_q
outputs.append(Y)
return torch.cat(outputs, dim=0), (H,)
与rnn不同的是:只要传入初始化参数,初始化state,以及forward如何计(定义的gru)丢尽RNNModel即可运算。
vocab_size, num_hiddens, device = len(vocab), 256, d2l.try_gpu()
num_epochs, lr = 500, 1
model = d2l.RNNModelScratch(len(vocab), num_hiddens, device, get_params,
init_gru_state, gru)
d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device)
经过nn的直接调用的RNN或GRU,得到的将X(bs,V)送进去这个net得到的都是Y(T,bs,h),都需要额外添加Linear(h,V)得到最终的outputs(T*bs,V)
再与y(bs,T)转置reshape得到的(T*bs)计算交叉熵loss
num_inputs = vocab_size
gru_layer = nn.GRU(num_inputs, num_hiddens)
model = d2l.RNNModel(gru_layer, len(vocab))
model = model.to(device)
d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device)
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
def get_lstm_params(vocab_size, num_hiddens, device):
num_inputs = num_outputs = vocab_size
def normal(shape):
return torch.randn(size=shape, device=device)*0.01
def three():
return (normal((num_inputs, num_hiddens)),
normal((num_hiddens, num_hiddens)),
torch.zeros(num_hiddens, device=device))
W_xi, W_hi, b_i = three() # 输⼊⻔参数
W_xf, W_hf, b_f = three() # 遗忘⻔参数
W_xo, W_ho, b_o = three() # 输出⻔参数
W_xc, W_hc, b_c = three() # 候选记忆元参数
# 输出层参数
W_hq = normal((num_hiddens, num_outputs))
b_q = torch.zeros(num_outputs, device=device)
# 附加梯度
params = [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc,
b_c, W_hq, b_q]
for param in params:
param.requires_grad_(True)
return params
def init_lstm_state(batch_size, num_hiddens, device):
return (torch.zeros((batch_size, num_hiddens), device=device),
torch.zeros((batch_size, num_hiddens), device=device))
有了c记忆元的存在,所以要初始化两个。
def lstm(inputs, state, params):
[W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c,
W_hq, b_q] = params
(H, C) = state
outputs = []
for X in inputs:
I = torch.sigmoid((X @ W_xi) + (H @ W_hi) + b_i)
F = torch.sigmoid((X @ W_xf) + (H @ W_hf) + b_f)
O = torch.sigmoid((X @ W_xo) + (H @ W_ho) + b_o)
C_tilda = torch.tanh((X @ W_xc) + (H @ W_hc) + b_c)
C = F * C + I * C_tilda
H = O * torch.tanh(C)
Y = (H @ W_hq) + b_q
outputs.append(Y)
return torch.cat(outputs, dim=0), (H, C)
vocab_size, num_hiddens, device = len(vocab), 256, d2l.try_gpu()
num_epochs, lr = 500, 1
model = d2l.RNNModelScratch(len(vocab), num_hiddens, device, get_lstm_params,
init_lstm_state, lstm)
d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device)
送入for X,T in train_iter里面的X,Y均为(bs,T)
X直接送入net会先经过one-hot变成(T,bs,V)
经过net后得到的y_hat为(T*bs,V)
在net中,如果是调用nn.RNN(len(vocab),num_hiddens)或者gru或lstm,则通过调用层得到的Y尺寸都为(T,bs,hiddens),本质上是所有时间步的隐层,需要再接一个LInear(h,V)得到输出y_hat为(T*bs,V)。
如果是从零实现,则得到的每一个Y为(bs,V),再通过dim=0的累加得到y_hat为(T*bs,V)。
然后在于y(经过转置为(T*bs))进行交叉熵计算loss。