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 #144

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
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
7 changes: 5 additions & 2 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from PIL import Image
import torch
from torchvision import transforms
from main import Net # Importing Net class from main.py
from main import Net, TrainModel # Importing Net and TrainModel classes from main.py

# Load the model
model = Net()
Expand All @@ -14,6 +14,9 @@
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
# Create an instance of TrainModel
train_model = TrainModel(model, criterion, optimizer, trainloader)
train_model.train(3)

app = FastAPI()

Expand All @@ -23,6 +26,6 @@ async def predict(file: UploadFile = File(...)):
image = transform(image)
image = image.unsqueeze(0) # Add batch dimension
with torch.no_grad():
output = model(image)
output = train_model.model(image)
_, predicted = torch.max(output.data, 1)
return {"prediction": int(predicted[0])}
29 changes: 20 additions & 9 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,23 @@
trainset = datasets.MNIST('.', download=True, train=True, transform=transform)
trainloader = DataLoader(trainset, batch_size=64, shuffle=True)

# Step 4: Define the TrainModel Class
class TrainModel:
def __init__(self, model, criterion, optimizer, dataloader):
self.model = model
self.criterion = criterion
self.optimizer = optimizer
self.dataloader = dataloader

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

# Step 2: Define the PyTorch Model
class Net(nn.Module):
def __init__(self):
Expand All @@ -35,14 +52,8 @@ def forward(self, x):
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()
# Create an instance of TrainModel and train
train_model = TrainModel(model, criterion, optimizer, trainloader)
train_model.train(3)

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