Understanding Tensor¶
In [1]:
Copied!
import torch
torch.cuda.is_available()
import torch
torch.cuda.is_available()
Out[1]:
False
In [21]:
Copied!
import torch
tensor0d = torch.tensor(1)
tensor1d = torch.tensor([1, 2, 3])
tensor2d = torch.tensor([[1, 2],
[3, 4]])
tensor3d = torch.tensor([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
tensor4d = torch.tensor([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]])
import torch
tensor0d = torch.tensor(1)
tensor1d = torch.tensor([1, 2, 3])
tensor2d = torch.tensor([[1, 2],
[3, 4]])
tensor3d = torch.tensor([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
tensor4d = torch.tensor([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]])
In [3]:
Copied!
tensor1d = torch.tensor([1, 2, 3])
print(tensor1d.dtype)
tensor1d = torch.tensor([1, 2, 3])
print(tensor1d.dtype)
torch.int64
In [4]:
Copied!
floatvec = torch.tensor([1.0, 2.0, 3.0])
print(floatvec.dtype)
floatvec = torch.tensor([1.0, 2.0, 3.0])
print(floatvec.dtype)
torch.float32
In [7]:
Copied!
floatvec = tensor1d.to(torch.float32)
print(tensor1d)
print(floatvec)
print(floatvec.dtype)
floatvec = tensor1d.to(torch.float32)
print(tensor1d)
print(floatvec)
print(floatvec.dtype)
tensor([1, 2, 3]) tensor([1., 2., 3.]) torch.float32
In [8]:
Copied!
tensor2d = torch.tensor([[1, 2, 3],
[4, 5, 6]])
print(tensor2d)
tensor2d = torch.tensor([[1, 2, 3],
[4, 5, 6]])
print(tensor2d)
tensor([[1, 2, 3],
[4, 5, 6]])
In [22]:
Copied!
print(tensor2d.shape)
print(tensor3d.shape)
print(tensor4d.shape)
print(tensor2d.shape)
print(tensor3d.shape)
print(tensor4d.shape)
torch.Size([2, 2]) torch.Size([2, 2, 2]) torch.Size([1, 2, 2, 2])
Reshape Tensor¶
In [11]:
Copied!
print(tensor2d.reshape(3, 2))
print(tensor2d.view(3, 2))
print(tensor2d.reshape(3, 2))
print(tensor2d.view(3, 2))
tensor([[1, 2],
[3, 4],
[5, 6]])
tensor([[1, 2],
[3, 4],
[5, 6]])
Transpose Tensor¶
In [12]:
Copied!
print(tensor2d.T)
print(tensor2d.T)
tensor([[1, 4],
[2, 5],
[3, 6]])
Matrix Multiplication¶
In [14]:
Copied!
print(tensor2d.matmul(tensor2d.T))
print(tensor2d @ tensor2d.T)
print(tensor2d.matmul(tensor2d.T))
print(tensor2d @ tensor2d.T)
tensor([[14, 32],
[32, 77]])
tensor([[14, 32],
[32, 77]])
In [ ]:
Copied!