Chapter 4: Pytorch, Using Jupyter Notebooks

by digitaltech2.com
pytorch juypter notebooks

Jupyter Notebooks provide an interactive environment for developing and visualizing your code. They are widely used in data science and machine learning for experimenting with code, documenting workflows, and sharing results.

Installing Jupyter Notebooks

To use Jupyter Notebooks with PyTorch, you need to install the Jupyter package in your virtual environment. Here’s how you can do it:

Activate your virtual environment:

source myenv/bin/activate  # or myenv\Scripts\activate on Windows

Install Jupyter:

pip install jupyter
Launching Jupyter Notebooks

Once Jupyter is installed, you can start a new notebook server:

Launch Jupyter Notebook:

jupyter notebook

Create a New Notebook:

  • Open your web browser and navigate to http://localhost:8888/.
  • Click on “New” and select “Python 3” to create a new notebook.
Example: Using Jupyter Notebooks with PyTorch

Here’s an example of how to use Jupyter Notebooks with PyTorch. We’ll create a simple notebook to demonstrate basic tensor operations:

Create a new notebook and rename it to PyTorch_Tutorial.ipynb.

Add and execute the following cells:

Cell 1: Import PyTorch

import torch
print("PyTorch version:", torch.__version__)

Cell 2: Create Tensors

# Create a tensor
tensor_a = torch.tensor([1, 2, 3, 4])
print("Tensor A:", tensor_a)

# Create a random tensor
tensor_b = torch.randn((3, 3))
print("Tensor B:\n", tensor_b)

Cell 3: Tensor Operations

# Add two tensors
tensor_c = tensor_a + 10
print("Tensor C (A + 10):", tensor_c)

# Multiply two tensors
tensor_d = tensor_a * 2
print("Tensor D (A * 2):", tensor_d)

Save and run the notebook.

Visualization with Matplotlib

Jupyter Notebooks are also great for visualizing data. Here’s an example of how to plot data using Matplotlib in a notebook:

Add and execute the following cell:

import matplotlib.pyplot as plt

# Generate some data
x = torch.linspace(0, 10, steps=100)
y = torch.sin(x)

# Plot the data
plt.plot(x.numpy(), y.numpy())
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

This cell generates a sine wave and plots it using Matplotlib, demonstrating the integration of PyTorch with other popular Python libraries within a Jupyter Notebook.

Related Posts