0、 LSTM 原理
整理优秀的文章
LSTM入门例子:根据前9年的数据预测后3年的客流(PyTorch实现)
[干货]深入浅出LSTM及其Python代码实现
整理视频
李毅宏手撕LSTM
[双语字幕]吴恩达深度学习deeplearning.ai
1 Pytorch 代码
这里直接调用了nn.lstm
self.lstm = nn.LSTM(input_size, hidden_size, num_layers) # utilize the LSTM model in torch.nn
下面作为初学者解释一下里面的3个参数
input_size: 这个就是输入的向量的长度or 维度,如一个单词可能占用20个维度。
hidden_size: 这个是隐藏层,其实我感觉有点全连接的意思,这个层的维度影响LSTM 网络输入的维度,换句话说,LSTM接收的数据维度不是输入什么维度就是什么维度,而是经过了隐藏层,做了一个维度的转化。
num_layers: 这里就是说堆叠了几个LSMT 结构。
2 网络定义
class LstmRNN(nn.Module):"""Parameters:- input_size: feature size- hidden_size: number of hidden units- output_size: number of output- num_layers: layers of LSTM to stack"""def __init__(self, input_size, hidden_size=1, output_size=1, num_layers=1):super().__init__()self.lstm = nn.LSTM(input_size, hidden_size, num_layers) # utilize the LSTM model in torch.nnself.forwardCalculation = nn.Linear(hidden_size, output_size)def forward(self, _x):x, _ = self.lstm(_x) # _x is input, size (seq_len, batch, input_size)s, b, h = x.shape # x is output, size (seq_len, batch, hidden_size)x = x.view(s * b, h)x = self.forwardCalculation(x)x = x.view(s, b, -1)return x
3 网络初始化
我们定义一个网络导出onnx ,观察 网络的具体结构
INPUT_FEATURES_NUM = 100
OUTPUT_FEATURES_NUM = 13
lstm_model = LstmRNN(INPUT_FEATURES_NUM, 16, output_size=OUTPUT_FEATURES_NUM, num_layers=2) # 16 hidden units
print(lstm_model)
save_onnx_path= "weights/lstm_16.onnx"
input_data = torch.randn(1,150,100)input_names = ["images"] + ["called_%d" % i for i in range(2)]
output_names = ["prob"]
torch.onnx.export(lstm_model,input_data,save_onnx_path,verbose=True,input_names=input_names,output_names=output_names,opset_version=12)
可以看到 LSTM W 是1x64x100;这个序列150没有了 是不是说150序列是一次一次的送的呢,所以在网络中没有体现;16是hidden,LSTM里面的W是64,这里存在一个4倍的关系。
我想这个关系和LSTM的3个门(输入+输出+遗忘+C^)有联系。
这里输出我们设置的13,如图 onnx 网络结构可视化显示也是13,至于这个150,或许就是输入有150个词,输出也是150个词吧。
至于LSTM的层数设置为2,则表示有2个LSTM堆叠。
4 网络提取
另外提取 网络方便看 每一层的维度,代码如下。
import onnx
from onnx import helper, checker
from onnx import TensorProto
import re
import argparse
model = "./weights/lstm_16.onnx"
output_model_path = "./weights/lstm_16_e.onnx"onnx_model = onnx.load(model)
#Flatten
onnx.utils.extract_model(model, output_model_path, ['images'],['prob'])