今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

Building LSTMs with PyTorch and Lightning AI Part 1: First Steps with LSTMs

Rijul Rajesh 2026年06月22日 02:25 2 次阅读 来源:Dev.to

In this article, we will explore how to implement an LSTM using PyTorch and Lightning . For more details about LSTMs, there is a separate series of articles available here . Imports To begin, we first import the required modules. import torch import torch.nn as nn import torch.nn.functional as F Introducing a New Optimizer We also introduce a new optimizer: from torch.optim import Adam Adam is used to fit the neural network to the data. It works similarly to SGD, but in practice, Adam often converges faster and adapts the learning rate more effectively. Lightning and Data Utilities Next, we continue with the remaining imports: import lightning as L from torch.utils.data import TensorDataset , DataLoader Defining the LSTM Model We define the neural network by creating a Lightning module. class LSTMByHand ( L . LightningModule ): def __init__ ( self ): # Create and initialize weight and bias tensors def lstm_unit ( self , input_value , long_memory , short_memory ): # LSTM computations def forward ( self , input ): # Forward pass through the unrolled LSTM def configure_optimizers ( self ): # Configure Adam optimizer def training_step ( self , batch , batch_idx ): # Compute loss and log training progress Initializing the Model Now let’s implement the __init__ method. This is where we initialize all weights and biases. class LSTMByHand ( L . LightningModule ): def __init__ ( self ): super (). __init__ () mean = torch . tensor ( 0.0 ) # Mean of the normal distribution std = torch . tensor ( 1.0 ) # Standard deviation # ------------------------- # Forget Gate (l = "lr") # ------------------------- self . wlr1 = nn . Parameter ( torch . normal ( mean = mean , std = std ), requires_grad = True ) self . wlr2 = nn . Parameter ( torch . normal ( mean = mean , std = std ), requires_grad = True ) self . blr1 = nn . Parameter ( torch . tensor ( 0.0 ), requires_grad = True ) # ------------------------- # Input Gate (p = "pr") # ------------------------- self . wpr1 = nn . Parameter

本文内容来源于互联网,版权归原作者所有
查看原文