Learn practical skills, build real-world projects, and advance your career
Updated 4 years ago
Working with Tensors
Five Interesting Function in PyTorch
An short introduction about PyTorch and about the chosen functions.
- view()
- torch.mean()
- torch.squeeze()
- torch.log()
- stride()
# Import torch and other required modules
import torch
Function 1 - view()
This function is used to change the shape of the existing tensor and returns a new tensor with the same elements but of a different shape.
view(*shape) → Tensor
# Example 1 - working
x=torch.ones(5,5, dtype=torch.int)
print(x)
print(x.size())
y=x.view(25)
print(y)
print(y.size())
tensor([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]], dtype=torch.int32)
torch.Size([5, 5])
tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1], dtype=torch.int32)
torch.Size([25])
As you can see, initially, the size of the tensor is [5,5], and later we have formed a new tensor with the same number of elements that have the size [25].