帮助网站源码,最好的淘宝网站建设,wordpress导航站源码,完整网站建设案例教程0、 LSTM 原理
整理优秀的文章 LSTM入门例子#xff1a;根据前9年的数据预测后3年的客流#xff08;PyTorch实现#xff09; [干货]深入浅出LSTM及其Python代码实现 整理视频 李毅宏手撕LSTM [双语字幕]吴恩达深度学习deeplearning.ai
1 Pytorch 代码
这里直接调用了nn.l…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 stackdef __init__(self, input_size, hidden_size1, output_size1, num_layers1):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 x3 网络初始化
我们定义一个网络导出onnx 观察 网络的具体结构
INPUT_FEATURES_NUM 100
OUTPUT_FEATURES_NUM 13
lstm_model LstmRNN(INPUT_FEATURES_NUM, 16, output_sizeOUTPUT_FEATURES_NUM, num_layers2) # 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,verboseTrue,input_namesinput_names,output_namesoutput_names,opset_version12)可以看到 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.onnxonnx_model onnx.load(model)
#Flatten
onnx.utils.extract_model(model, output_model_path, [images],[prob])