ModuleNotFoundError Error

Hello all,

I am building a basic deep learning model using PyTorch for image classification-

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

# Define a simple feedforward neural network
class NeuralNetwork(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNetwork, self).__init()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

# Hyperparameters
input_size = 784  # Example: 28x28 images
hidden_size = 128
num_classes = 10
learning_rate = 0.001
num_epochs = 5

# Load and preprocess data (MNIST dataset)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transform, download=True)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)

# Initialize the model
model = NeuralNetwork(input_size, hidden_size, num_classes)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.view(-1, 28 * 28)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backpropagation and optimization
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        if (i+1) % 100 == 0:
            print(f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f}')

# Test the model on test data (not shown here)

# Save the model
torch.save(model.state_dict(), 'model.ckpt')

When I run the code, it’s showing the below error-

Output:

Traceback (most recent call last):
File “main.py”, line 1, in
import torch
ModuleNotFoundError: No module named ‘torch’

Any solution will highly be appreciated.

Thanks

Although you’re importing torch in your python file, the error message indicates that the PyTorch library is not installed in your Python environment.

If you use pip, you can install Pytorch via: pip install torch torchvision

If you’ve previously done this and are using a virtual environment, make sure it’s activated.

Lastly, to help you get unstuck in the future, copying and pasting this question into ChatGPT, Bing AI or Bard are great ways to work through similar issues :grinning: Happy coding!