Jovian
⭐️
Sign In
In [1]:
import torch
In [2]:
t1 = torch.tensor(4.); t1
Out[2]:
tensor(4.)
In [3]:
t1.dtype
Out[3]:
torch.float32
In [4]:
t_1 = torch.tensor(4); t_1.dtype
Out[4]:
torch.int64
In [5]:
#Vector

t2 = torch.tensor([1., 2, 3, 4])
t2
Out[5]:
tensor([1., 2., 3., 4.])
In [8]:
#matrix

t3 = torch.tensor([[5.,6.], [7.,8], [9,10]]);t3
Out[8]:
tensor([[ 5.,  6.],
        [ 7.,  8.],
        [ 9., 10.]])
In [9]:
# 3-dimensional array
t4 = torch.tensor([
    [[11, 12, 13],
    [13, 14, 15]],
    [[15,16,17],
    [17,18,19]]
]);t4
Out[9]:
tensor([[[11, 12, 13],
         [13, 14, 15]],

        [[15, 16, 17],
         [17, 18, 19]]])
In [10]:
t1.shape
Out[10]:
torch.Size([])
In [11]:
t2.shape
Out[11]:
torch.Size([4])
In [12]:
t2
Out[12]:
tensor([1., 2., 3., 4.])
In [13]:
t3.shape
Out[13]:
torch.Size([3, 2])
In [14]:
t3
Out[14]:
tensor([[ 5.,  6.],
        [ 7.,  8.],
        [ 9., 10.]])
In [16]:
t4.shape
Out[16]:
torch.Size([2, 2, 3])
In [17]:
t4
Out[17]:
tensor([[[11, 12, 13],
         [13, 14, 15]],

        [[15, 16, 17],
         [17, 18, 19]]])
In [18]:
# Create tensors
x = torch.tensor(3.)
w = torch.tensor(4., requires_grad=True)
b = torch.tensor(5., requires_grad=True)
In [19]:
y = w * x + b; y
Out[19]:
tensor(17., grad_fn=<AddBackward0>)
In [20]:
# compute derivatives
y.backward()
In [23]:
#Display gradients
print('dy/dx:', x.grad)
print('dy/dw:', w.grad)
print('dy/db:', b.grad)
dy/dx: None dy/dw: tensor(3.) dy/db: tensor(1.)
In [24]:
import numpy as np

x = np.array([[1, 2], [3, 4]])
x
Out[24]:
array([[1, 2],
       [3, 4]])
In [25]:
#convert the numpy array to a torch tensor.
y = torch.from_numpy(x)
In [26]:
y
Out[26]:
tensor([[1, 2],
        [3, 4]])
In [27]:
x.dtype, y.dtype
Out[27]:
(dtype('int64'), torch.int64)
In [28]:
# Convert a torch tensor to a numpy array
z = y.numpy()
y
Out[28]:
tensor([[1, 2],
        [3, 4]])
In [ ]:
import jovian
jovian.commit()
[jovian] Please enter your API key (from https://jvn.io ): ········ [jovian] Saving notebook..
In [ ]: