[Pytorch] First day
import torch
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
Content one
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)
print(type(x), type(w), type(b))
y = w * x + b
y.backward()
print(x.grad)
print(w.grad)
print(b.grad)
tensor(2.)
tensor(1.)
tensor(1.)
Content two
x = torch.randn(10, 3)
y = torch.randn(10, 2)
linear = nn.Linear(3, 2)
print('w: ', linear.weight)
print('b: ', linear.bias)
w: Parameter containing:
tensor([[ 0.2271, 0.4796, -0.4287],
[ 0.3378, -0.5249, 0.2095]], requires_grad=True)
b: Parameter containing:
tensor([0.4186, 0.1931], requires_grad=True)
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(linear.parameters(), lr=0.01)
pred = linear(x)
loss = criterion(pred, y)
print('loss:', loss.item())
loss: 1.1817594766616821
loss.backward()
print('dl/dw: ', linear.weight.grad)
print('dl/db: ', linear.bias.grad)
dl/dw: tensor([[-0.5055, 0.2931, -0.8895],
[ 0.0444, 0.0985, 0.4994]])
dl/db: tensor([ 0.6998, -0.0333])
optimizer.step()
pred = linear(x)
loss = criterion(pred, y)
print('loss after 1 step optimization: ',loss.item())
loss after 1 step optimization: 1.1630728244781494
Content three
x = np.array([[1, 2], [3, 4]])
y = torch.from_numpy(x)
z = y.numpy()
print(type(x), type(y), type(z))
Content four
train_dataset = torchvision.datasets.CIFAR10(root='../../data',
train=True,
transform=transforms.ToTensor(),
download=True)
print(type(train_dataset))
image, label = train_dataset[0]
print(image.size)
print(label)
Files already downloaded and verified
6
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=64,
shuffle=True)
data_iter = iter(train_loader)
images, labels = data_iter.__next__()
for images, labels in train_loader:
pass
Content five
class CustomDataset(torch.utils.data.Dataset):
def __init__(self):
pass
def __getitem__(self, index):
pass
def __len__(self):
return 0
custom_dataset = CustomDataset()
train_loader = torch.utils.data.DataLoader(dataset=custom_dataset,
batch_size=64,
shuffle=False)
Content six
resnet = torchvision.models.resnet18(pretrained=True)
for param in resnet.parameters():
param.requires_grad = False
resnet.fc = nn.Linear(resnet.fc.in_features, 100)
images = torch.randn(64, 3, 224, 224)
outputs = resnet(images)
print(outputs.size())
/home/wsl_ubuntu/anaconda3/envs/xy_trans/lib/python3.8/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.
warnings.warn(
/home/wsl_ubuntu/anaconda3/envs/xy_trans/lib/python3.8/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.
warnings.warn(msg)
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /home/wsl_ubuntu/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
100%|██████████| 44.7M/44.7M [00:20<00:00, 2.34MB/s]
torch.Size([64, 100])
Content seven
torch.save(resnet, 'model.ckpt')
model = torch.load('model.ckpt')
torch.save(resnet.state_dict(), 'params.ckpt')
resnet.load_state_dict(torch.load('params.ckpt'))