Pytorch is an open source machine learning library based on the torch library used for applications such as computer vision and natural language processing.
Pytorch defines a class called tensor(torch.tensor) to store and operations on homogeneous multidimensional rectangular array of number.
Pytorch tensor is the fundamental unit of the pytorch framework whose operation are similar to python numpy array. Convert python list to pytorch tensor.
import torch
import numpy as np
t =torch.tensor([[15., -33.,44.], [-81., -54., 55]])
t
tensor([[ 15., -33., 44.],
[-81., -54., 55.]])
t1=torch.tensor(np.array([[45, 27, 63], [144, 549, 72]]))
t1
tensor([[ 45, 27, 63],
[144, 549, 72]])
t2 =torch.zeros([3,4])
t2
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
t4 =torch.ones([3,3])
t4
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
t3 =torch.randn([3,3])
t3
tensor([[-1.2749, 1.9119, 0.1540],
[ 0.2169, 1.6054, 0.0332],
[-0.2685, -0.8797, 2.6951]])
Simple join the tensor
x = torch.tensor([[45, 27, 63], [144, 549, 45]])
y = torch.tensor([[4, 5, 9], [5.4, 6.3, 9.1]])
t1 =torch.cat([x,y],dim=1)
t1
tensor([[ 45.0000, 27.0000, 63.0000, 4.0000, 5.0000, 9.0000],
[144.0000, 549.0000, 45.0000, 5.4000, 6.3000, 9.1000]])
import torch
import numpy as np
x =torch.tensor([[32,45,86],[33,65,73]])
y =torch.tensor([[22,33,21],[45,33,35]])
x1=torch.add(x,y)
x1
tensor([[ 54, 78, 107],
[ 78, 98, 108]])
x2 =torch.tensor([[20,20,20],[20,20,20]])
x3 =torch.tensor([[45,66,45],[33,55,76]])
x4 =torch.sub(x,y)
x4
tensor([[ 10, 12, 65],
[-12, 32, 38]])
x5 =torch.mul(x,y)
x5
tensor([[ 704, 1485, 1806],
[1485, 2145, 2555]])
x6 =torch.div(x,y)
x6
tensor([[1.4545, 1.3636, 4.0952],
[0.7333, 1.9697, 2.0857]])
import torch
from torchvision import datasets
from torchvision.transforms import ToTensor
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
import matplotlib.pyplot as plt
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
Firstly i learn what is pytorch than i performed the basic operation i.e convert python list to pytorch tensor then pytorch zero tensor then ones tensor than random tensor then perfomed simple mathematical operation. then i performed how we can load the dataset from torchvision. then i performed visulization on the dataset with the help of matplotlib to visulize some images in our training dataset.