Python PyTorch – torch.linalg.solve() Function
Last Updated :
10 Jun, 2022
In this article, we will discuss torch.linalg.solve() method in PyTorch.
Example:
Let's consider the linear equations :
6x + 3y = 1
3x - 4y = 2
Then M values can be - [[6,3],[3,-4]]
and t is [1,2]
torch.linalg.solve() Function
The torch.linalg.solve() method is used to solve a square system of linear equations with a unique solution. It will take two parameters, in which the first parameter is a matrix that is a tensor and the second parameter is also a tensor with one dimension.
Syntax: torch.linalg.solve(M, t)
Parameters:
- M is an tensor matrix
- t is a tensor vector.
Return: It will return a tensor.
Example1:
In this example, we will Solve the linear equation – 6x + 3y = 1, 3x – 4y = 2 and check the solution is true or not. Here M is [[6,3],[3,-4]] and t [1,2]. After that we will apply torch.linalg.solve() method to return unique tensor solution. Finally we will use torch.allclose() method to check the equation is true or not.
Python3
import torch
M = torch.tensor([[ 6. , 3. ], [ 3. , - 4. ]])
t = torch.tensor([ 1. , 2. ])
solved = torch.linalg.solve(M, t)
print (solved)
print (torch.allclose(M @ solved, t))
|
Output:
tensor([ 0.3030, -0.2727])
True
Example 2:
In this example, we will Solve the linear equation – 6x + 3y = 1,3x – 4y = 2 and check the solution is true or not. Here the elements of M is [[6,3],[3,-4]] and t is [0,2]. After that, we will apply torch.linalg.solve() method which will return a unique tensor solution. Finally, we will use a torch.allclose() method to check whether the equation is true or not.
Python3
import torch
M = torch.tensor([[ 5. , - 3. ], [ 3. , - 4. ]])
t = torch.tensor([ 0. , 2. ])
solved = torch.linalg.solve(M, t)
print (solved)
print (torch.allclose(M @ solved, t))
|
Output:
tensor([-0.5455, -0.9091])
True
Example 3:
In this example, we will Solve the linear equation – 9x – y = 0, 3x – 4y = 0 and check the solution is true or not. Here the elements of M is [[9,-1],[3,-4]] and t [0,0]. After that, we will apply the torch.linalg.solve() method which will return a unique tensor solution, and last we will use a torch.allclose() method to check whether the equation is true or not.
Python3
import torch
M = torch.tensor([[ 9. , - 1. ], [ 3. , - 4. ]])
t = torch.tensor([ 0. , 0. ])
solved = torch.linalg.solve(M, t)
print (solved)
print (torch.allclose(M @ solved, t))
|
Output:
tensor([0., -0.])
True
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...