PyTorch is an open-source framework available with a Python programming language. Tensor is a multidimensional array that is used to store the data. To use a tensor, we have to import the torch module. To create a tensor, the method used is tensor().
Syntax:
Where the data is a multi-dimensional array.
Torch.trace()
Trace is computed as the sum of diagonal elements in a matrix.
Syntax:
Parameter:
It takes a tensor object as a parameter which is a 2D tensor.
Example 1:
Let’s create a tensor that has 4 rows and 4 columns and return the trace of the tensor matrix.
import torch
#create a 2D tensor matrix
data1 = torch.tensor([[2,3,4,5],[3,1,2,3],[2,4,5,6],[5,6,7,0]])
#display
print("Actual Tensor matrix: ")
print(data1)
print("Trace of a matrix: ")
#return trace
print(torch.trace(data1))
Output:
tensor([[2, 3, 4, 5],
[3, 1, 2, 3],
[2, 4, 5, 6],
[5, 6, 7, 0]])
Trace of a matrix:
tensor(8)
The sum of diagonals is: 2+1+5+0 = 8. Hence, the trace is 8.
Example 2:
Let’s create a tensor that has 2 rows and 2 columns and return the trace of the tensor matrix.
import torch
#create a 2D tensor matrix
data1 = torch.tensor([[2,33],[3,1]])
#display
print("Actual Tensor matrix: ")
print(data1)
print("Trace of a matrix: ")
#return trace
print(torch.trace(data1))
Output:
tensor([[ 2, 33],
[ 3, 1]])
Trace of a matrix:
tensor(3)
The sum of diagonals is: 2+1 = 3. Hence, the trace is 3.
Work with CPU
If you want to run the trace() function on the CPU, we have to create a tensor with a cpu() function. This will run on a CPU machine.
When we create a tensor, this time, we can use the cpu() function.
Syntax:
Example 1:
Let’s create a tensor that has 4 rows and 4 columns on the cpu and return the trace of the tensor matrix.
import torch
#create a 2D tensor matrix
data1= torch.tensor([[2,3,4,5],[3,1,2,3],[2,4,5,6],[5,6,7,0]]).cpu()
#display
print("Actual Tensor matrix: ")
print(data1)
print("Trace of a matrix: ")
#return trace
print(torch.trace(data1))
Output:
tensor([[2, 3, 4, 5],
[3, 1, 2, 3],
[2, 4, 5, 6],
[5, 6, 7, 0]])
Trace of a matrix:
tensor(8)
The sum of diagonals is: 2+1+5+0 = 8. Hence, the trace is 8.
Example 2:
Let’s create a tensor that has 2 rows and 2 columns on the cpu and return the trace of the tensor matrix.
import torch
#create a 2D tensor matrix
data1 = torch.tensor([[2,33],[3,1]]).cpu()
#display
print("Actual Tensor matrix: ")
print(data1)
print("Trace of a matrix: ")
#return trace
print(torch.trace(data1))
Output:
tensor([[ 2, 33],
[ 3, 1]])
Trace of a matrix:
tensor(3)
The sum of diagonals is: 2+1 = 3. Hence, the trace is 3.
Conclusion
In this PyTorch lesson, we discussed about the trace() function. It returns the sum of diagonal elements in a matrix. We also discussed the different examples and worked these examples on a cpu machine.