PyTorch

PyTorch is a famous tool to build neural networks which can be used with Python .

Installation

First, install PyTorch using pip:

BASH
pip install torch torchvision
Click to expand and view more

Building a Simple Neural Network

Step 1: Import Required Libraries

PYTHON
import torch
import torch.nn as nn
import torch.optim as optim
Click to expand and view more

Step 2: Define the Network Architecture

PYTHON
class SimpleNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(SimpleNN, self).__init__()
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.layer2 = nn.Linear(hidden_size, output_size)
    
    def forward(self, x):
        x = self.layer1(x)
        x = self.relu(x)
        x = self.layer2(x)
        return x
Click to expand and view more

Step 3: Initialize the Model

PYTHON
# Define dimensions
input_size = 10
hidden_size = 20
output_size = 2

# Create model instance
model = SimpleNN(input_size, hidden_size, output_size)
Click to expand and view more

Step 4: Define Loss Function and Optimizer

PYTHON
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
Click to expand and view more

Step 5: Training Loop

PYTHON
# Example training loop
for epoch in range(100):
    # Forward pass
    outputs = model(train_data)
    loss = criterion(outputs, train_labels)
    
    # Backward pass and optimization
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')
Click to expand and view more

Key Concepts

Conclusion

PyTorch makes it easy to build and train neural networks with its intuitive API and automatic differentiation capabilities. This simple example demonstrates the core workflow that can be extended to more complex architectures.

…..

Copyright Notice

Author: Hugo Narrow

Link: http://localhost:1313/posts/how-to-build-and-train-a-simple-neural-network-using-pytorch/

License: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut