MNIST-NN-WebGUI/train.py

72 lines
2.0 KiB
Python
Raw Normal View History

2024-09-19 12:57:16 +08:00
import os
import torch
import torchvision
from torchvision import datasets, transforms
from torch import nn, optim
2024-09-19 16:43:50 +08:00
lr = 0.8
bs = 64
epochs = 50
2024-09-19 12:57:16 +08:00
# Set device
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Define transformations
transform = transforms.Compose([
transforms.ToTensor(),
2024-09-19 16:43:50 +08:00
#transforms.Normalize((0.5,), (0.5,))
2024-09-19 12:57:16 +08:00
])
# Load MNIST dataset
train_dataset = datasets.MNIST(root='data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
# Define the neural network model
2024-09-19 16:43:50 +08:00
class MNISTNN(nn.Module):
2024-09-19 12:57:16 +08:00
def __init__(self):
2024-09-19 16:43:50 +08:00
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Linear(512, 10)
)
2024-09-19 12:57:16 +08:00
def forward(self, x):
2024-09-19 16:43:50 +08:00
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
2024-09-19 12:57:16 +08:00
# Instantiate the model
2024-09-19 16:43:50 +08:00
model = MNISTNN().to(device)
2024-09-19 12:57:16 +08:00
# Define loss function and optimizer
2024-09-19 16:43:50 +08:00
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=lr)
2024-09-19 12:57:16 +08:00
# Check if the model already exists
2024-09-19 16:43:50 +08:00
model_path = 'mnist_model_2.pth'
2024-09-19 12:57:16 +08:00
start_epoch = 0
if os.path.isfile(model_path):
model.load_state_dict(torch.load(model_path))
print("Loaded existing model.")
# Optionally load the epoch if you save that too
# start_epoch = <load_saved_epoch>
# Train the model
for epoch in range(start_epoch, start_epoch + epochs):
running_loss = 0
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
2024-09-19 16:43:50 +08:00
preds = model(images)
loss = loss_fn(preds, labels)
2024-09-19 12:57:16 +08:00
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch + 1}/{start_epoch + epochs}, Loss: {running_loss/len(train_loader)}")
# Save the trained model
torch.save(model.state_dict(), model_path)
print("Model saved!")