💾 Archived View for gem.sdf.org › s.kaplan › cheatsheets › libraries-and-frameworks › pytorch.md captured on 2023-11-04 at 12:11:02.
⬅️ Previous capture (2023-09-08)
-=-=-=-=-=-=-
# PyTorch Cheatsheet PyTorch is a popular open-source machine learning library based on the Torch library. It provides easy-to-use APIs for building and training deep neural networks. This cheatsheet provides a quick reference for some of PyTorch's unique features, including code blocks for variables, functions, loops, conditionals, file manipulation, and more. Additionally, it includes a list of resources for further learning. ## Variables
import torch
x = torch.tensor([1, 2, 3])
y = torch.tensor([[1, 2], [3, 4]])
x.shape
x.ndim
x.size()
x.reshape(3, 1)
torch.cat((x, x))
x.max()
## Functions
import torch.nn.functional as F
F.softmax(x, dim=0)
F.relu(x)
F.cross_entropy(y_pred, y_true)
## Loops and Conditionals
for i in range(10):
print(i)
while x < 10:
print(x)
x += 1
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
## File Manipulation
import torch
torch.save(x, 'x.pt')
x = torch.load('x.pt')
## Other Useful Features
import torch
torch.manual_seed(42)
x.cuda()
x.requires_grad = True
y = x**2
y.backward()
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
## Resources - [PyTorch documentation](https://pytorch.org/docs/stable/index.html) - [PyTorch tutorials](https://pytorch.org/tutorials/) - [Deep Learning with PyTorch book](https://pytorch.org/assets/deep-learning/Deep-Learning-with-PyTorch.pdf)