PyTorch Tensors
The basic building block for Pytorch is a tensor. A tensor is an n-dimensional array that support multiple numeric and boolean types for machine learning tasks. They are an extension of numpy arrays but have computational properties that make them suitable to high-dimensional mathematical operations which are required for Machine Learning and especially Deep Learning.
Creating a Tensor
The following example creates a Tensor using the
# importing packages: torch and numpy
import torch
import numpy as np
x = torch.tensor([1, 2, 3])
x
Size Property
The size property returns the number of elements in a tensor by the given dimension.
x.size()
Here is another example of a $2x2$ tensor creation.
# 2 x 2 tensor with size 2
y = torch.tensor([[1, 2],
[3, 4]])
# 2 x 2 tensor with size 3
z = torch.tensor([[2, 3, 4],
[6, 3, 3],
[0, 1, 4]])
print("The size of Tensor y is:", y.size(), "\n"
"The size of Tensor z is:", z.size())
x.dim(), b.dim(), z.dim()
x.size(), y.size(), z.size()
Float Tensors
As noted earlier, tensors can store different numeric types. This becomes important when training deep learning models as unexpected numeric types will result in errors during training or the development process.
torch.FloatTensor([[1, 2], [2, 1]])
Alternatively, you can define Float tensors
torch.tensor( [[1, 2], [2, 1]], dtype=torch.float32)
Boolean Tensors
We can also define tensors as
torch.tensor( [[1, 0, 2], [5, -3, 0]], dtype=torch.bool)