Gregor Lenz
26.7.2022
model = nn.Sequential(nn.Linear(...), nn.Linear(...))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
device = 'cuda:0'
for epoch in range(10):
model.train()
for data, y_true in iter(training_dataloader):
data = data.to(device)
targets = targets.to(device)
optimizer.zero_grad()
y_hat = model(data)
loss = criterion(y_hat, y_true)
loss.backward()
optimizer.step()
# log the loss
...
model.eval()
# log the epoch loss, evaluate
...
import pytorch_lightning as pl
class MyLightningModel(pl.LightningModule):
def __init__(self):
# define model here...
def forward(self, data: torch.Tensor):
# specify how data is fed to the model
def training_step(self, batch):
# unpack a mini-batch, feed data, calculate losses
def validation_step(self, batch):
# unpack a mini-batch, feed data, calculate losses,
# calculate prediction accuracy
def configure_optimizers(self):
# specify optimizer here