Learn practical skills, build real-world projects, and advance your career
Updated 4 years ago
PyTorch Tensor manipulation
Learning how to use torch.Tensor class
In this notebook we have experimented with some of the functions included in the torch.Tensor class from the PyTorch package. These are the functions we have used:
- torch.tensor
- zeros and new_zeros
- fill_diagonal
- permute
- expand
# Import torch and other required modules
import torch
import numpy as np
Function 1 - torch.tensor
The "tensor" function is the most basic and fundamental one from the whole PyTorch and it is used for constructing tensors. Note that torch.tensor is an allias for the default tensor type "torch.FloatTensor"
# Example 1 - Define a 2 by 2 matrix, either from a list or a np array
x = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor(np.array([[5., 6.],[7., 8.]]))
print(x,"\n",y)
tensor([[1, 2],
[3, 4]])
tensor([[5., 6.],
[7., 8.]], dtype=torch.float64)
As you can see, the Tensor function is useful to define tensors (n-dimentional matrixes).