PyTorch 深度学习进阶
Michal Oleszak
Machine Learning Engineer


xhyh
h 与 y 相同三个输入与输出(两个隐藏状态):
h:短期状态c:长期状态三个"门":
class Net(nn.Module): def __init__(self, input_size): super().__init__()self.lstm = nn.LSTM( input_size=1, hidden_size=32, num_layers=2, batch_first=True, ) self.fc = nn.Linear(32, 1)def forward(self, x): h0 = torch.zeros(2, x.size(0), 32) c0 = torch.zeros(2, x.size(0), 32)out, _ = self.lstm(x, (h0, c0))out = self.fc(out[:, -1, :]) return out
__init__():nn.RNN 替换为 nn.LSTMforward():cc 与 h 用零初始化lstm 层
class Net(nn.Module): def __init__(self, input_size): super().__init__()self.gru = nn.GRU( input_size=1, hidden_size=32, num_layers=2, batch_first=True, ) self.fc = nn.Linear(32, 1)def forward(self, x): h0 = torch.zeros(2, x.size(0), 32) out, _ = self.gru(x, h0) out = self.fc(out[:, -1, :]) return out
__init__():nn.RNN 替换为 nn.GRUforward():gru 层
PyTorch 深度学习进阶