Open your terminal or command prompt and run the following commands:
pip install notebook
pip install torch torchvision torchaudio
Run this command in the terminal:
jupyter notebook
The Jupyter interface will open in your browser.
In the Jupyter interface, click on New → Python 3 to create a new notebook.
import torch
print(torch.__version__)
You should see the version number without errors.
x = torch.tensor([[1, 2], [3, 4]])
print(x)
y = x + 5
print(y)
print(torch.cuda.is_available())
import torch.nn as nn
import torch.optim as optim
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.layer = nn.Linear(2, 1)
def forward(self, x):
return self.layer(x)
model = SimpleModel()
print(model)
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
targets = torch.tensor([[1.0], [2.0]])
loss_fn = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
for epoch in range(100):
optimizer.zero_grad()
outputs = model(inputs)
loss = loss_fn(outputs, targets)
loss.backward()
optimizer.step()
print("Training completed!")
You've successfully trained a simple neural network using PyTorch inside Jupyter Notebook!