forked from SkafteNicki/dtu_mlops
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4533436
commit 8222c0e
Showing
2 changed files
with
149 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
s4_debugging_and_logging/exercise_files/lightning_solution.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import pytorch_lightning as pl | ||
import torch | ||
from torch import nn | ||
|
||
|
||
class MyAwesomeModel(pl.LightningModule): | ||
"""My awesome model.""" | ||
|
||
def __init__(self) -> None: | ||
super().__init__() | ||
self.conv1 = nn.Conv2d(1, 32, 3, 1) | ||
self.conv2 = nn.Conv2d(32, 64, 3, 1) | ||
self.conv3 = nn.Conv2d(64, 128, 3, 1) | ||
self.dropout = nn.Dropout(0.5) | ||
self.fc1 = nn.Linear(128, 10) | ||
|
||
self.loss_fn = nn.CrossEntropyLoss() | ||
|
||
def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
"""Forward pass.""" | ||
x = torch.relu(self.conv1(x)) | ||
x = torch.max_pool2d(x, 2, 2) | ||
x = torch.relu(self.conv2(x)) | ||
x = torch.max_pool2d(x, 2, 2) | ||
x = torch.relu(self.conv3(x)) | ||
x = torch.max_pool2d(x, 2, 2) | ||
x = torch.flatten(x, 1) | ||
x = self.dropout(x) | ||
x = self.fc1(x) | ||
return x | ||
|
||
def training_step(self, batch): | ||
"""Training step.""" | ||
img, target = batch | ||
y_pred = self(img) | ||
loss = self.loss_fn(y_pred, target) | ||
return loss | ||
|
||
def configure_optimizers(self): | ||
"""Configure optimizer.""" | ||
return torch.optim.Adam(self.parameters(), lr=1e-3) | ||
|
||
|
||
if __name__ == "__main__": | ||
model = MyAwesomeModel() | ||
print(f"Model architecture: {model}") | ||
print(f"Number of parameters: {sum(p.numel() for p in model.parameters())}") | ||
|
||
dummy_input = torch.randn(1, 1, 28, 28) | ||
output = model(dummy_input) | ||
print(f"Output shape: {output.shape}") |