Pytorch Demo 1749471354
Pytorch Demo 1749471354
One of the key advantages of PyTorch is its support for GPU acceleration, allowing
you to train models on GPUs to significantly speed up computations. It also has a
large and active community, which means there are plenty of resources, tutorials,
and pre-trained models available.
In [ ]: import torch
Tensors
In [ ]: # Number/Scalar
t1 = torch.tensor(4.)
t1
In [ ]: t1.dtype
In [ ]: #Vector
t2 = torch.tensor([1., 2, 3, 4])
t2
In [ ]: # Matrix
t3 = torch.tensor([
[5., 6],
[7,8],
[9,10]
])
t3
In [ ]: # 3 dimensional array
t4 = torch.tensor([
[
[11, 12, 13],
[14, 15, 16]
],
[
[17,18,19],
[20,21,22]
]
])
t4
In [ ]: print(t1)
t1.shape
In [ ]: print(t2)
t2.shape
In [ ]: print(t3)
t3.shape
In [ ]: print(t4)
t4.shape
x = torch.tensor(3.)
w = torch.tensor(4. , requires_grad = True)
b = torch.tensor(5., requires_grad = True)
x, w, b
In [ ]: # Arithemitc operations
y = w*x + b
y
In [ ]: # Compute derivates
y.backward()
In [ ]: # Display gradients
print("dy/dx: " ,x.grad)
print("dy/dw: ", w.grad)
print("dy/db: ", b.grad)
In [ ]:
Tensor functions
In [ ]: # Create a tensor with a fixed value for every elemnt
t6 = torch.full((3,2), 42)
t6
In [ ]: y = torch.from_numpy(x)
y
In [ ]: x.dtype, y.dtype
In [ ]: z = y.numpy()
z
In [ ]:
inputs = np.array([
[73, 67,43],
[91, 88, 64],
[87, 134, 58],
[102, 43, 37],
[69, 96, 70],
], dtype = 'float32')
target = np.array([
[56, 70],
[81, 101],
[119, 113],
[22, 37],
[103, 119]
], dtype = 'float32')
inputs = torch.from_numpy(inputs)
target = torch.from_numpy(target)
print(inputs)
print(target)
print(w)
print(b)
# Z = X * W + B
def model(x):
return x @ w.t() + b
In [ ]: # prediction
preds = model(inputs)
print(preds)
return torch.sum(diff*diff)/diff.numel()
In [ ]: # error
loss = MSE(target, preds)
print(loss)
In [ ]: #Compute gradients
loss.backward()
In [ ]: print(w)
print(w.grad)
In [ ]: print(b)
print(b.grad)
In [ ]: #reset grad
w.grad.zero_()
b.grad.zero_()
print(w.grad)
print(b.grad)
In [ ]: # Adjust params
preds = model(inputs)
print(preds)
In [ ]: loss.backward()
print(w.grad)
print(b.grad)
learning_rate = 1e-5
with torch.no_grad():
w -= w.grad * 1e-5
b -= b.grad * 1e-5
w.grad.zero_()
b.grad.zero_()
In [ ]: print(w)
print(b)
In [ ]: # Calculate again
preds = model(inputs)
loss = MSE(target, preds)
print(loss)
w.grad.zero_()
b.grad.zero_()
print(f"Epochs({i}/{100}) & Loss {loss}")
In [ ]: preds = model(inputs)
loss = MSE(target, preds)
print(loss)
In [ ]: preds
In [ ]: target
In [ ]:
training_data = datasets.FashionMNIST(
root = 'data',
train= True,
download = True,
transform = ToTensor(),
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download = True,
transform = ToTensor(),
)
In [ ]: type(training_data)
In [ ]: batch_size = 64
for X, y in test_dataloader:
print("Shape of X [N, C, H, W] ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
model= NeuralNetwork().to(device)
print(model)
loss_fn = nn.CrossEntropyLoss()
In [ ]: # Model Training
# BackPropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
In [ ]: epochs = 1
for t in range(epochs):
print(f"Epoch {t+1} \n --------------------------")
train(train_dataloader, model, loss_fn, optimizer)
test(test_dataloader, model, loss_fn)
print("Done\n")
In [ ]:
In [ ]: #save model
torch.save(model.state_dict(), "model.pth")
print("Saved model state to model.pth")
In [ ]: ## Prediction
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot"
model.eval()
x, y = test_data[10][0], test_data[10][1]
x = x.to(device)
# y = y.to(device)
with torch.no_grad():
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
In [ ]: