Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Flask Tutorial
Next article icon

What is PyTorch ?

Last Updated : 01 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

PyTorch is a deep learning library built on Python and Torch (a Lua-based framework). It provides GPU acceleration, dynamic computation graphs, and an intuitive interface for deep learning researchers and developers. PyTorch follows a “define-by-run” approach, meaning that its computational graphs are constructed on the fly, allowing for better debugging and model customization.

Key Features of PyTorch

  • PyTorch uses dynamic graphs, allowing flexibility in model execution and debugging.
  • PyTorch provides an automatic differentiation engine that simplifies gradient computation for deep learning.
  • PyTorch supports CUDA, allowing computations to be performed efficiently on GPUs.

How to Install PyTorch?

PyTorch can be installed on Windows, macOS, and Linux using pip for CPU (without GPU):

!pip install torch torchvision torchaudio

PyTorch Tensors

Tensors are the fundamental data structures in PyTorch, similar to NumPy arrays but with GPU acceleration capabilities. PyTorch tensors support automatic differentiation, making them suitable for deep learning tasks.

Python
import torch  # Creating a 1D tensor x = torch.tensor([1.0, 2.0, 3.0]) print('1D Tensor: \n', x)  # Creating a 2D tensor y = torch.zeros((3, 3)) print('2D Tensor: \n', y) 

Output:

1D Tensor:
tensor([1., 2., 3.])

2D Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])

Operations on Tensors

Python
a = torch.tensor([1.0, 2.0]) b = torch.tensor([3.0, 4.0])  # Element-wise addition print('Element Wise Addition of a & b: \n', a + b)  # Matrix multiplication print('Matrix Multiplication of a & b: \n',        torch.matmul(a.view(2, 1), b.view(1, 2))) 

Output:

Element Wise Addition of a & b:
tensor([4., 6.])

Matrix Multiplication of a & b:
tensor([[3., 4.],
[6., 8.]])

Reshaping and Transposing Tensors

Python
import torch  t = torch.tensor([[1, 2, 3, 4],                  [5, 6, 7, 8],                  [9, 10, 11, 12]])  # Reshaping print("Reshaping") print(t.reshape(6, 2))  # Resizing (deprecated, use reshape) print("\nResizing") print(t.view(2, 6))  # Transposing print("\nTransposing") print(t.transpose(0, 1)) 

Output:

Reshaping
tensor([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])

Resizing
tensor([[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12]])

Transposing
tensor([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])

Autograd and Computational Graphs

The autograd module automates gradient calculation for backpropagation. This is crucia in training deep neural networks.

Python
x = torch.tensor(2.0, requires_grad=True) y = x ** 2 y.backward() print(x.grad)  #(dy/dx = 2x = 4 when x=2) 

Output:

tensor(4.)

PyTorch dynamically creates a computational graph that tracks operations and gradients for backpropagation.

Building Neural Networks in PyTorch

In PyTorch, neural networks are built using the torch.nn module, where:

  • nn.Linear(in_features, out_features) defines a fully connected (dense) layer.
  • Activation functions like torch.relu, torch.sigmoid, or torch.softmax are applied between layers.
  • forward() method defines how data moves through the network.

To build a neural network in PyTorch, we create a class that inherits from torch.nn.Module and defines its layers and forward pass.

Python
class NeuralNetwork(nn.Module):     def __init__(self):         super(NeuralNetwork, self).__init__()         self.fc1 = nn.Linear(10, 16)  # First layer         self.fc2 = nn.Linear(16, 8)   # Second layer         self.fc3 = nn.Linear(8, 1)    # Output layer      def forward(self, x):         x = torch.relu(self.fc1(x))         x = torch.relu(self.fc2(x))         x = torch.sigmoid(self.fc3(x))          return x  model = NeuralNetwork() print(model) 

Output:

NeuralNetwork(
(fc1): Linear(in_features=10, out_features=16, bias=True)
(fc2): Linear(in_features=16, out_features=8, bias=True)
(fc3): Linear(in_features=8, out_features=1, bias=True)
)

Define Loss Function and Optimizer

Once we define our model, we need to specify:

  • A loss function to measure the error.
  • An optimizer to update the weights based on computed gradients.

We use nn.BCELoss() for binary cross-entropy loss and used optim.Adam() for Adam optimizer to combine the benefits of momentum and adaptive learning rates.

Python
model = NeuralNetwork() criterion = nn.BCELoss()   optimizer = torch.optim.Adam(model.parameters(), lr=0.01) 

Train the Model

The training involves:

  1. Generating dummy data (100 samples, each with 10 features).
  2. Running a training loop where we:
    • optimizer.zero_grad() clears the accumulated gradients from the previous step.
    • Forward Pass (model(inputs)) passes inputs through the model to generate predictions.
    • Loss Computation (criterion(outputs, targets)) computes the difference between predictions and actual labels.
    • Backpropagation (loss.backward()) computes gradients for all weights.
    • Optimizer Step (optimizer.step()) updates the weights based on the computed gradients.
Python
inputs = torch.randn((100, 10))  targets = torch.randint(0, 2, (100, 1)).float()   epochs = 20  for epoch in range(epochs):     optimizer.zero_grad()  # Reset gradients     outputs = model(inputs)  # Forward pass     loss = criterion(outputs, targets)  # Compute loss     loss.backward()  # Compute gradients     optimizer.step()  # Update weights      if (epoch+1) % 5 == 0:         print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}") 

Output:

Epoch [5/20], Loss: 0.7014
Epoch [10/20], Loss: 0.6906
Epoch [15/20], Loss: 0.6744
Epoch [20/20], Loss: 0.6483

PyTorch vs TensorFlow

FeaturePyTorchTensorFlow
Computational GraphDynamicStatic (TF 1.x), Dynamic (TF 2.0)
Ease of UsePythonic, easy to debugSteeper learning curve
PerformanceFast with eager executionOptimized for large-scale deployment
DeploymentTorchScript & ONNXTensorFlow Serving & TensorFlow Lite
Popularity in ResearchWidely usedAlso widely used but more in production

Applications of PyTorch

  1. Computer Vision: PyTorch is widely used in image classification, object detection, and segmentation using CNNs and Transformers (e.g., ViT).
  2. Natural Language Processing (NLP): PyTorch supports transformers, recurrent neural networks (RNNs), and LSTMs for applications like text generation and sentiment analysis.
  3. Reinforcement Learning: PyTorch is used in Deep Q-Networks (DQN), Policy Gradient Methods, and Actor-Critic Algorithms.
  4. Healthcare and Bioinformatics: Used in medical image analysis, drug discovery, and protein structure prediction.

PyTorch is used in academia and industry for computer vision, NLP, and reinforcement learning applications. With its strong community support and easy-to-use API, PyTorch continues to be one of the leading deep learning frameworks.



Next Article
Flask Tutorial
author
d2anubis
Improve
Article Tags :
  • AI-ML-DS
  • Deep Learning
  • Python-PyTorch

Similar Reads

  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
  • Python Fundamentals

    • Python Introduction
      Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code. Key Features of PythonPython’s simple and readable syntax makes it beginner-frie
      3 min read

    • Input and Output in Python
      Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
      8 min read

    • Python Variables
      In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
      7 min read

    • Python Operators
      In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
      6 min read

    • Python Keywords
      Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. List of Keywords in PythonTrueFalseNoneandornotisifelseelifforwhilebreakconti
      12 min read

    • Python Data Types
      Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
      10 min read

    • Conditional Statements in Python
      Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations. If Conditional Statement in PythonIf statement is the simplest form of a conditional st
      6 min read

    • Loops in Python - For, While and Nested Loops
      Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
      10 min read

    Python Functions

    • Python def Keyword
      Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def
      6 min read

    • Python return statement
      A return statement is used to end the execution of the function call and it "returns" the value of the expression following the return keyword to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is
      4 min read

    • Global and Local Variables in Python
      Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only insid
      7 min read

    • Recursion in Python
      Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks. In Python, a recursive function is defined like any other func
      6 min read

    • *args and **kwargs in Python
      In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs. Example: [GFGTABS] Python # *args example def fun(*args): return sum(args) print(fun
      4 min read

    • Python Lambda Functions
      Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
      7 min read

    • Python map() function
      The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
      4 min read

    Python Data Structures

    • Python String
      A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
      6 min read

    • Python Lists
      In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
      6 min read

    • Python Tuples
      A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
      7 min read

    • Dictionaries in Python
      A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
      5 min read

    • Python Sets
      Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change. Creating a Set in PythonIn Python, the most basic and efficient method for creatin
      11 min read

    • Python Arrays
      Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
      10 min read

    • List Comprehension in Python
      List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques. For example
      4 min read

  • Python OOPs Concepts
    Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
    11 min read
  • Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
    7 min read
  • File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
  • Python Database Handling

    • Python MongoDB Tutorial
      MongoDB is one of the most popular NoSQL database. It is a cross-platform, object-oriented database. Basically NoSQL means MongoDB does not store data in the table or relational format rather provide a different mechanism for storage and retrieval of data. This is called BSON which is similar to JSO
      3 min read

    • Python MySQL
      Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library.  This Python MySQL tutorial will
      9 min read

    Python Packages or Libraries

    • Python Modules
      Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
      7 min read

    • Python DSA Libraries
      Data Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
      15+ min read

    • List of Python GUI Library and Packages
      Graphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
      12 min read

    Data Science with Python

    • Python NumPy
      Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Besides its obvious scientific uses, Numpy can also be used as an efficient
      6 min read

    • Pandas Tutorial
      Pandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
      7 min read

    • Matplotlib Tutorial
      Matplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
      5 min read

    • Introduction to Seaborn - Python
      Prerequisite - Matplotlib Library  Visualization is an important part of storytelling, we can gain a lot of information from data by simply just plotting the features of data. Python provides a numerous number of libraries for data visualization, we have already seen the Matplotlib library in this a
      5 min read

    • StatsModel Library- Tutorial
      Statsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
      4 min read

    • Learning Model Building in Scikit-learn
      Building machine learning models from scratch can be complex and time-consuming. However with the right tools and frameworks this process can become significantly easier. Scikit-learn is one such tool that makes machine learning model creation easy. It provides user-friendly tools for tasks like Cla
      10 min read

    • XGBoost
      Traditional machine learning models like decision trees and random forests are easy to interpret but often struggle with accuracy on complex datasets. XGBoost, short for eXtreme Gradient Boosting, is an advanced machine learning algorithm designed for efficiency, speed, and high performance. What is
      9 min read

    • TensorFlow Tutorial
      TensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
      3 min read

    • What is PyTorch ?
      PyTorch is a deep learning library built on Python and Torch (a Lua-based framework). It provides GPU acceleration, dynamic computation graphs, and an intuitive interface for deep learning researchers and developers. PyTorch follows a "define-by-run" approach, meaning that its computational graphs a
      5 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences