Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor training loop from script to class #8

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,29 @@ def forward(self, x):
x = self.fc3(x)
return nn.functional.log_softmax(x, dim=1)

# Step 3: Train the Model
# Step 3: Define the Trainer class
class Trainer:
def __init__(self, model, optimizer, criterion, trainloader):
self.model = model
self.optimizer = optimizer
self.criterion = criterion
self.trainloader = trainloader

def train(self, epochs):
for epoch in range(epochs):
for images, labels in self.trainloader:
self.optimizer.zero_grad()
output = self.model(images)
loss = self.criterion(output, labels)
loss.backward()
self.optimizer.step()

# Step 4: Train the Model
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01)
criterion = nn.NLLLoss()

# Training loop
epochs = 3
for epoch in range(epochs):
for images, labels in trainloader:
optimizer.zero_grad()
output = model(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
trainer = Trainer(model, optimizer, criterion, trainloader)
trainer.train(3)

torch.save(model.state_dict(), "mnist_model.pth")
Loading