之前写过PyTorch建设深度神经网络,这一次是上一篇文章的连续,将介绍RNN,LSTM,GRU相干模型搭建。
RNN、GRU、LSTM均是领有“记忆”性能的网络模块,在模型参数上基本相同。
建设RNN模型
# 定义网络结构class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.rnn = nn.RNN(input_size=28, # 输出特色的大小 hidden_size=64, # RNN模块(block)的数量,随便设置 num_layers=1, # 示意RNN层的层数 batch_first=True) # RNN默认输出的格局是[seq_len, batch, feature] # batch_first=True示意格局变成[batch, seq_len, feature] # 这里的64和hidden_size的64绝对应 self.out = nn.Linear(64, 10) self.softmax = nn.Softmax(dim=1) def forward(self, x): inputs = x.reshape((x.shape[0],28, -1)) # output:[batch, seq_len, hidden_size] # 尽管RNN的batch_first为True,然而h_n,c_n第一个维度还是num_layers # h_n:[num_layers*num_directions, batch, hidden_size] 只蕴含最初一个序列的隐层后果,示意h_t # num_directions:取值为1或2,示意是否为双向RNN output, h_n = self.rnn(inputs) output_in_last_timestep = h_n[-1, :, :] x = self.out(output_in_last_timestep) out = self.softmax(x) return out
建设LSTM模型
# 定义网络结构class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.lstm = nn.LSTM(input_size=28, # 输出特色的大小 hidden_size=64, # LSTM模块(block)的数量,随便设置 num_layers=1, # 示意LSTM层的层数 batch_first=True) # LSTM默认输出的格局是[seq_len, batch, feature] # batch_first=True示意格局变成[batch, seq_len, feature] # 这里的64和hidden_size的64绝对应 self.out = nn.Linear(64, 10) self.softmax = nn.Softmax(dim=1) def forward(self, x): inputs = x.reshape((x.shape[0],28, -1)) # output:[batch, seq_len, hidden_size] # 尽管LSTM的batch_first为True,然而h_n,c_n第一个维度还是num_layers # h_n:[num_layers*num_directions, batch, hidden_size] 只蕴含最初一个序列的输入后果,示意h_t # c_n:[num_layers*num_directions, batch, hidden_size] 只蕴含最初一个序列的cell后果,示意c_t # num_directions:取值为1或2,示意是否为双向LSTM output, (h_n, c_n) = self.lstm(inputs) output_in_last_timestep = h_n[-1, :, :] x = self.out(output_in_last_timestep) out = self.softmax(x) return out
定义双向LSTM模型须要在nn.LSTM
中增加参数bidirectional=True
定义GRU模型
# 定义网络结构class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.gru = nn.GRU(input_size=28, # 输出特色的大小 hidden_size=64, # GRU模块(block)的数量,随便设置 num_layers=1, # 示意GRU层的层数 batch_first=True) # GRU默认输出的格局是[seq_len, batch, feature] # batch_first=True示意格局变成[batch, seq_len, feature] # 这里的64和hidden_size的64绝对应 self.out = nn.Linear(64, 10) self.softmax = nn.Softmax(dim=1) def forward(self, x): inputs = x.reshape((x.shape[0],28, -1)) # output:[batch, seq_len, hidden_size*num_directions] # 尽管GRU的batch_first为True,然而h_n,c_n第一个维度还是num_layers # h_n:[num_layers*num_directions, batch, hidden_size] 只蕴含最初一个序列的输入后果,示意h_t # num_directions:取值为1或2,示意是否为双向GRU output, h_n = self.gru(inputs) output_in_last_timestep = h_n[-1, :, :] x = self.out(output_in_last_timestep) out = self.softmax(x) return out
模型加载与保留
PyTorch容许用户保留和加载已训练实现的模型
# 保留模型torch.save(model.state_dict(), 'model/GRUModel.pth')# 加载模型model.load_state_dict(torch.load('model/GRUModel.pth'))
模型显示
Keras创立的模型能够应用summary
办法显示模型相干参数,PyTorch也领有一个库torchsummary
能够用来显示模型参数
应用pip命令即可装置
pip install torchsummary
显示模型参数只须要两行代码
from torchsummary import summarysummary(model, (28, 28))