How to use PyTorch in a notebook?

Dec 15, 2025

Leave a message

PyTorch has emerged as a leading open - source machine learning library, favored by researchers and developers for its dynamic computational graphs and ease of use. As a notebook supplier, I've seen an increasing demand from customers who want to use notebooks to experiment with PyTorch. In this blog, I'll guide you through the process of using PyTorch in a notebook environment, whether it's a physical A6 Leather Journal for jotting down ideas or a digital notebook like Jupyter Notebook for actual coding.

Why Use a Notebook for PyTorch?

Notebooks offer a unique advantage when working with PyTorch. They provide an interactive environment where you can write, run, and modify code in small, manageable chunks. You can also add text explanations, visualizations, and markdown cells to document your thought process. This makes notebooks an ideal tool for prototyping, exploring data, and sharing your work with others.

Setting Up Your Environment

Before you can start using PyTorch in a notebook, you need to set up your environment. Here are the steps:

1. Install Python

PyTorch is a Python library, so you need to have Python installed on your system. You can download the latest version of Python from the official Python website (python.org). It's recommended to use Python 3.6 or higher.

2. Install PyTorch

There are several ways to install PyTorch. The easiest way is to use the official PyTorch installation command, which you can find on the PyTorch website (pytorch.org). The command will vary depending on your operating system, CUDA version (if you want to use GPU acceleration), and the package manager you prefer (pip or conda).

For example, if you're using pip on a CPU - only system, you can use the following command:

pip install torch torchvision

3. Install a Notebook Environment

There are several notebook environments available, but Jupyter Notebook is the most popular one. You can install Jupyter Notebook using pip:

pip install jupyter

Once installed, you can start Jupyter Notebook by running the following command in your terminal:

jupyter notebook

This will open a new browser window with the Jupyter Notebook dashboard, where you can create and manage your notebooks.

Getting Started with PyTorch in a Notebook

Now that your environment is set up, let's start using PyTorch in a notebook.

1. Importing PyTorch

The first step in any PyTorch project is to import the library. In a Jupyter Notebook cell, you can do this as follows:

import torch

You can also import other useful libraries, such as torchvision for computer vision tasks:

import torchvision
import torchvision.transforms as transforms

2. Working with Tensors

Tensors are the fundamental data structure in PyTorch. They are similar to NumPy arrays but can be used on GPUs for faster computation. You can create a tensor in PyTorch like this:

# Create a 2x3 tensor
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x)

You can perform various operations on tensors, such as addition, multiplication, and reshaping. For example:

# Add two tensors
y = torch.tensor([[7, 8, 9], [10, 11, 12]])
z = x + y
print(z)

3. Building a Simple Neural Network

One of the most common use cases of PyTorch is building neural networks. Here is a simple example of a neural network for classifying handwritten digits using the MNIST dataset:

import torch.nn as nn
import torch.nn.functional as F

# Define a simple neural network
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

net = Net()

# Load the MNIST dataset
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5,), (0.5,))])

trainset = torchvision.datasets.MNIST(root='./data', train=True,
                                      download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
                                          shuffle=True)

# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# Train the network
for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        if i % 200 == 199:
            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 200:.3f}')
            running_loss = 0.0

print('Finished Training')

Using Notebooks for Documentation and Experimentation

As a notebook supplier, I understand the importance of using notebooks not only for coding but also for documentation and experimentation. You can use markdown cells in Jupyter Notebook to write detailed explanations of your code, document your experiments, and share your findings.

For example, you can write a markdown cell to explain the purpose of the neural network you just built:

### Explanation of the Neural Network
The neural network we built is a simple feed - forward network with two fully connected layers. The first layer takes an input of size 784 (the flattened image of a 28x28 handwritten digit) and maps it to 128 hidden units. The second layer maps the 128 hidden units to 10 output units, corresponding to the 10 digit classes (0 - 9).

We used the ReLU activation function in the first layer to introduce non - linearity, and the output layer uses the softmax function implicitly through the `CrossEntropyLoss` function.

You can also use notebooks to experiment with different hyperparameters, such as learning rate, batch size, and number of hidden units. By keeping track of your experiments in a notebook, you can easily compare the results and choose the best configuration.

Our Notebook Offerings

As a notebook supplier, we offer a wide range of notebooks that can be used for PyTorch development. Whether you need a Spiral Notebook with Hardcover for taking notes during your coding sessions or Sticky Transparent Notes for marking important code snippets, we have you covered.

China Notebook SupplierSticky Transparent Notes

Our notebooks are made from high - quality materials and are designed to meet the needs of professionals and students alike. They come in various sizes, colors, and styles, so you can choose the one that suits your preferences.

Contact Us for Procurement

If you're interested in purchasing our notebooks for your PyTorch projects or any other office needs, we'd love to hear from you. Contact us to start a procurement discussion and find the best notebook solutions for your requirements.

References

  • PyTorch official documentation (pytorch.org/docs)
  • Jupyter Notebook official documentation (jupyter.org/documentation)
  • Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.

Send Inquiry