top of page

Getting Started with PyTorch in Python for Machine Learning

  • Writer: Anvita Shrivastava
    Anvita Shrivastava
  • Jun 25
  • 4 min read

Updated: Jun 26

Businesses use machine learning to analyze their data, automate processes, and develop intelligent applications. PyTorch has become one of the most widely used frameworks for people who do research, data science, and machine learning by allowing these individuals to create models quickly and easily in Python.


PyTorch was developed by Meta AI and offers a very flexible way to develop deep learning models in Python. This framework offers several benefits, such as strong community support, an easy-to-use dynamic computation graph, and seamless integration with the rest of the Python ecosystem, which makes it ideal for beginner and advanced users alike.


PyTorch in Python for Machine Learning
PyTorch in Python for Machine Learning

What is PyTorch?


PyTorch is a deep learning and AI framework developed as an open-source machine learning framework that simplifies the development of models using the Python programming language by providing automatic differentiation, GPU acceleration, and a Pythonic interface for model development, among other useful features.


Benefits of PyTorch:


  • Beginner Friendly.

  • Dynamic Computation Graphs.

  • Strong Support for Use of GPUs.

  • Extensive Libraries for Deep Learning.

  • Large Active Open-source Community.

  • Capability To Deploy Models to Production.


Over the years, PyTorch has become one of the most used frameworks in various industries, including, but not limited to: Health Care, Finance, Computer Vision, Natural Language Processing (NLP), and Recommendation Systems.


Why Use PyTorch for Machine Learning?


  1. It is beginner-friendly!


Compared to other programming languages, the syntax of PyTorch is extremely user-friendly. In addition, developers using the Python language will find that the syntax of PyTorch is similar to using NumPy.


  1. Dynamic Computation Graphs


Unlike previous frameworks that constructed a static graph of your model (like TensorFlow), PyTorch creates the computation graph of your model during execution, which means you will be able to debug your model more easily because it builds on the fly.


  1. Support For Use of GPUs


PyTorch is fully compatible with NVIDIA's CUDA technology. Using this technology helps significantly speed up the training of large ML models.


  1. Rich Ecosystem


PyTorch has built-in support for several popular libraries, including:


  • TorchVision for Image Data

  • TorchText for NLP

  • TorchAudio for Speech Data

  • PyTorch Lightning for Building ML Workflows


  1. Industry Adoption


All of the above advantages are what have led to the adoption of PyTorch by most of the world's leading companies and research institutions, developing innovative solutions based on artificial intelligence.


Getting Started with PyTorch in Python for Machine Learning


Installing PyTorch


Before building machine learning models, install PyTorch in your Python environment.

Using pip:

pip install torch torchvision torchaudio

Verify the installation:

import torch

print(torch.__version__)

Check GPU availability:

import torch

print(torch.cuda.is_available())

If the output is True, PyTorch can utilize your GPU for training.


Understanding Tensors in PyTorch


Tensors are the core data structures in PyTorch.

A tensor is similar to a NumPy array but can run on GPUs for accelerated computation.


Creating Tensors

import torch

x = torch.tensor([1, 2, 3, 4])
print(x)

Output:

tensor([1, 2, 3, 4])

Creating Multi-Dimensional Tensors

matrix = torch.tensor([
    [1, 2],
    [3, 4]
])

print(matrix)

Random Tensors

random_tensor = torch.rand(3, 3)

print(random_tensor)

Random tensors are commonly used to initialize neural network weights.


Basic Tensor Operations


PyTorch supports mathematical operations similar to NumPy.


Addition

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

print(a + b)

Multiplication

print(a * b)

Matrix Multiplication

x = torch.rand(2, 3)
y = torch.rand(3, 2)

result = torch.matmul(x, y)

print(result)

Efficient tensor operations are essential for deep learning computations.


Automatic Differentiation with Autograd


One of PyTorch's most powerful features is Autograd, which automatically calculates gradients during training.

Example:

import torch

x = torch.tensor(2.0, requires_grad=True)

y = x ** 2

y.backward()

print(x.grad)

Output:

tensor(4.)

Autograd enables backpropagation, which is the foundation of neural network training.


Building Your First Neural Network


PyTorch provides the torch.nn module for creating neural networks.


Simple Neural Network

import torch.nn as nn

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()

        self.layer1 = nn.Linear(10, 20)
        self.relu = nn.ReLU()
        self.layer2 = nn.Linear(20, 1)

    def forward(self, x):
        x = self.layer1(x)
        x = self.relu(x)
        x = self.layer2(x)

        return x

Create the model:

model = NeuralNetwork()

print(model)

This network contains:

  • Input layer

  • Hidden layer

  • ReLU activation function

  • Output layer


Training a Machine Learning Model in PyTorch


Training typically involves:

  1. Loading data

  2. Defining a model

  3. Choosing a loss function

  4. Selecting an optimizer

  5. Running training loops


Define Loss Function and Optimizer

import torch. optim as optim

criterion = nn.MSELoss()

optimizer = optim.Adam(
    model.parameters(),
    lr=0.001
)

Training Loop

for epoch in range(100):

    predictions = model(X_train)

    loss = criterion(
        predictions,
        y_train
    )

    optimizer.zero_grad()

    loss.backward()

    optimizer.step()

    print(
        f"Epoch {epoch}: {loss.item()}"
    )

The model learns by minimizing the loss over multiple iterations.


Working with Datasets and DataLoaders


PyTorch simplifies data management through the Dataset and DataLoader classes.


Example DataLoader

from torch. utils.data import DataLoader

train_loader = DataLoader(
    dataset=train_dataset,
    batch_size=32,
    shuffle=True
)

Benefits include:

  • Automatic batching

  • Data shuffling

  • Parallel loading

  • Improved training efficiency


Using GPUs with PyTorch


Training deep learning models on CPUs can be slow.

Move your model and data to a GPU:

device = torch.device(
    "cuda" if torch.cuda.is_available()
    else "cpu"
)

model.to(device)

Move tensors:

inputs = inputs.to(device)
labels = labels.to(device)

GPU acceleration can reduce training time significantly for large datasets.


Common PyTorch Applications


Computer vision applications include:


  • Image classification

  • Object detection

  • Facial recognition

  • Medical image analysis

  • Computer vision


Natural Language Processing


  • Chatbots

  • Sentiment analysis

  • Language translation

  • Text summarization

  • Recommendation systems


Many companies create personalized recommendation engines using PyTorch.


Generative AI


PyTorch powers many of the leading AI applications today, including:


  • Large language models

  • Generative AI tools

  • Image generation models


The growth of PyTorch as a major toolkit for developing machine learning and deep learning technology has placed it among the top frameworks today. Its Pythonic user interface, dynamic computational graphs, support for GPUs, and large ecosystem make PyTorch a great choice for both novice and advanced developers.


You will lay a strong foundation for building ML applications in PyTorch by learning about tensors, automatic differentiation, neural networks, training loops, and how to handle data.


You should also look into other advanced topics such as convolutional neural networks (CNNs), recurrent neural networks (RNNs), transformers, transfer learning, and large language models as you progress in your learning path. When you have completed the PyTorch curriculum, there will be many opportunities for developing AI and machine learning software solutions.


To learn more about PySheds and its geospatial capabilities, click here.


For more information or any questions regarding the LizardTech suite of products, please don't hesitate to contact us at:



USA (HQ): (720) 702–4849


(A GeoWGS84 Corp Company)



Comments


bottom of page