import os import sys import torch import torch.nn as nn import torch.nn.functional as F # Add this line import torchvision import torchvision.transforms as transforms sys.path.append("..") from tools import show seed = 4321 torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # device = torch.device("mps") # Hyper-parameters num_epochs = 1 batch_size = 64 learning_rate = 0.2 transform = transforms.Compose([transforms.ToTensor()]) train_dataset = torchvision.datasets.MNIST(root="./data", train=True, download=True, transform=transform) test_dataset = torchvision.datasets.MNIST(root="./data", train=False, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False) class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(1, 8, 5, 1, 0) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(8, 1, 5, 1, 0) self.fc1 = nn.Linear(1 * 4 * 4, 10) # self.fc2 = nn.Linear(120, 84) # self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(x.shape[0], -1) # x = F.relu(self.fc1(x)) # x = F.relu(self.fc2(x)) # x = self.fc3(x) x = self.fc1(x) return x def printFector(self, x, label): show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]), "input_image.png", Contrast=[0, 1.0]) # show.DumpTensorToLog(x, "input_image.log") x = self.conv1(x) w = self.conv1.weight show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]), "conv1_weight.png", Contrast=[-1.0, 1.0]) # show.DumpTensorToLog(w, "conv1_weight.log") show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]), "conv1_output.png", Contrast=[-1.0, 1.0]) # show.DumpTensorToLog(x, "conv1_output.png") x = self.pool(F.relu(x)) x = self.conv2(x) w = self.conv2.weight show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]).cpu(), "conv2_weight.png", Contrast=[-1.0, 1.0]) show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]).cpu(), "conv2_output.png", Contrast=[-1.0, 1.0]) x = self.pool(F.relu(x)) show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]).cpu(), "pool_output.png", Contrast=[-1.0, 1.0]) pool_shape = x.shape x = x.view(x.shape[0], -1) x = self.fc1(x) show.DumpTensorToImage( self.fc1.weight.view(-1, pool_shape[2], pool_shape[3]), "fc_weight.png", Contrast=[-1.0, 1.0] ) show.DumpTensorToImage(x.view(-1).cpu(), "fc_output.png") criterion = nn.CrossEntropyLoss() loss = criterion(x, label) optimizer.zero_grad() loss.backward() w = self.conv1.weight.grad show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]).cpu(), "conv1_weight_grad.png") w = self.conv2.weight.grad show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]), "conv2_weight_grad.png") show.DumpTensorToImage(self.fc1.weight.grad.view(-1, pool_shape[2], pool_shape[3]), "fc_weight_grad.png") model = ConvNet().to(device) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) # Train the model n_total_steps = len(train_loader) for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = images.to(device) labels = labels.to(device) # Forward pass outputs = model(images) loss = criterion(outputs, labels) # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() if (i + 1) % 100 == 0: print(f"Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}") test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False) for images, labels in test_loader: images = images.to(device) labels = labels.to(device) model.printFector(images, labels) break print("Finished Training") # Test the model with torch.no_grad(): n_correct = 0 n_samples = 0 for images, labels in test_loader: images = images.to(device) labels = labels.to(device) outputs = model(images) # max returns (value ,index) _, predicted = torch.max(outputs.data, 1) n_samples += labels.size(0) n_correct += (predicted == labels).sum().item() acc = 100.0 * n_correct / n_samples print(f"Accuracy of the network on the 10000 test images: {acc} %")