LSTMCell¶
- class LSTMCell(input_size, hidden_size, bias=True)[源代码]¶
A long short-term memory (LSTM) cell.
\[\begin{split}\begin{array}{ll} i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\ f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\ g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\ o = \sigma(W_{io} x + b_{io} + W_{ho} h + b_{ho}) \\ c' = f * c + i * g \\ h' = o * \tanh(c') \\ \end{array}\end{split}\]其中,\(\sigma\) 是 Hadamard 积。
- 参数
- Inputs: input, (h_0, c_0)
形状为 (batch, input_size) 的**input**:包含输入特征的tensor
形状为 (batch, hidden_size) 的**h_0**:包含batch中每个元素的初始 hidden state 的 tensor.
形状为 (batch, hidden_size) 的**c_0**:包含batch中每个元素的初始 cell state 的 tensor.
若 (h_0, c_0) 未提供,**h_0**和**c_0**默认设置为零。
- 输出:(h_1, c_1)
形状为 (batch, hidden_size) 的**h_1**:包含 batch 中每个元素下一个 hidden state 的 tensor.
形状为 (batch, hidden_size) 的**c_1**:包含 batch 中每个元素下一个 cell state 的 tensor.
实际案例
import numpy as np import megengine as mge import megengine.module as M m = M.LSTMCell(10, 20) inp = mge.tensor(np.random.randn(3, 10), dtype=np.float32) hx = mge.tensor(np.random.randn(3, 20), dtype=np.float32) cx = mge.tensor(np.random.randn(3, 20), dtype=np.float32) hy, cy = m(inp, (hx, cx)) print(hy.numpy().shape) print(cy.numpy().shape)
输出:
(3, 20) (3, 20)