In [0]:
import torch

In [2]:
## empty matrix
x = torch.empty(5,3)
x


Out[2]:
tensor([[1.8607e-35, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 2.8026e-45],
        [0.0000e+00, 1.1210e-44, 0.0000e+00],
        [1.4013e-45, 0.0000e+00, 0.0000e+00]])

In [4]:
## random matrix
x = torch.rand(3,2)
x


Out[4]:
tensor([[0.8732, 0.5434],
        [0.6724, 0.5409],
        [0.8621, 0.4036]])

In [6]:
## zero matrix with dtype as long. 
x = torch.zeros(5,3, dtype=torch.long)
x


Out[6]:
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

In [11]:
## prepare a tensor directly from data
data = [5.2, 3]
x = torch.tensor(data, dtype=torch.int)
x


Out[11]:
tensor([5, 3], dtype=torch.int32)

In [15]:
## create a new tensor from existing tensor by overriding
x = x.new_ones(2,2)

x = torch.randn_like(x, dtype=float)
x ## note the structure remains the same as the previous tensor


Out[15]:
tensor([[-1.3235,  0.7385],
        [ 3.0591,  0.0499]], dtype=torch.float64)

In [16]:
## size of tensor
x.size()


Out[16]:
torch.Size([2, 2])

In [18]:
## adding two tensors 
y = torch.rand(2,2)
print(y)
x.add(y)


tensor([[0.7648, 0.0676],
        [0.9298, 0.6317]])
Out[18]:
tensor([[-0.5587,  0.8061],
        [ 3.9888,  0.6815]], dtype=torch.float64)

In [21]:
print(x[:,1])


tensor([0.7385, 0.0499], dtype=torch.float64)

In [5]:
## numpy bridge

x = torch.ones(2,3)
x


Out[5]:
tensor([[1., 1., 1.],
        [1., 1., 1.]])

In [7]:
a = x.numpy()
a


Out[7]:
array([[1., 1., 1.],
       [1., 1., 1.]], dtype=float32)

In [0]: