幫企業(yè)做網(wǎng)站線(xiàn)上推廣的方法
0、 LSTM 原理
整理優(yōu)秀的文章
LSTM入門(mén)例子:根據(jù)前9年的數(shù)據(jù)預(yù)測(cè)后3年的客流(PyTorch實(shí)現(xiàn))
[干貨](méi)深入淺出LSTM及其Python代碼實(shí)現(xiàn)
整理視頻
李毅宏手撕LSTM
[雙語(yǔ)字幕]吳恩達(dá)深度學(xué)習(xí)deeplearning.ai
1 Pytorch 代碼
這里直接調(diào)用了nn.lstm
self.lstm = nn.LSTM(input_size, hidden_size, num_layers) # utilize the LSTM model in torch.nn
下面作為初學(xué)者解釋一下里面的3個(gè)參數(shù)
input_size: 這個(gè)就是輸入的向量的長(zhǎng)度or 維度,如一個(gè)單詞可能占用20個(gè)維度。
hidden_size: 這個(gè)是隱藏層,其實(shí)我感覺(jué)有點(diǎn)全連接的意思,這個(gè)層的維度影響LSTM 網(wǎng)絡(luò)輸入的維度,換句話(huà)說(shuō),LSTM接收的數(shù)據(jù)維度不是輸入什么維度就是什么維度,而是經(jīng)過(guò)了隱藏層,做了一個(gè)維度的轉(zhuǎn)化。
num_layers: 這里就是說(shuō)堆疊了幾個(gè)LSMT 結(jié)構(gòu)。
2 網(wǎng)絡(luò)定義
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 網(wǎng)絡(luò)初始化
我們定義一個(gè)網(wǎng)絡(luò)導(dǎo)出onnx ,觀(guān)察 網(wǎng)絡(luò)的具體結(jié)構(gòu)
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;這個(gè)序列150沒(méi)有了 是不是說(shuō)150序列是一次一次的送的呢,所以在網(wǎng)絡(luò)中沒(méi)有體現(xiàn);16是hidden,LSTM里面的W是64,這里存在一個(gè)4倍的關(guān)系。
我想這個(gè)關(guān)系和LSTM的3個(gè)門(mén)(輸入+輸出+遺忘+C^)有聯(lián)系。
這里輸出我們?cè)O(shè)置的13,如圖 onnx 網(wǎng)絡(luò)結(jié)構(gòu)可視化顯示也是13,至于這個(gè)150,或許就是輸入有150個(gè)詞,輸出也是150個(gè)詞吧。
至于LSTM的層數(shù)設(shè)置為2,則表示有2個(gè)LSTM堆疊。
4 網(wǎng)絡(luò)提取
另外提取 網(wǎng)絡(luò)方便看 每一層的維度,代碼如下。
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'])