HTML generated from Jupyter notebook: system-of-linear-equations.ipynb

Solving a system of linear equations using Pytorch

Solving $A \mathbf{x} = \mathbf{b}$

In [13]:
import torch

torch.manual_seed(0)

A = torch.randn(4,4)
b = torch.randn(4,1)

print('A:\n', A)
print('b:\n', b)

x = torch.mm(torch.inverse(A), b)
print('x:\n', x)
A:
 tensor([[-1.1258, -1.1524, -0.2506, -0.4339],
        [ 0.8487,  0.6920, -0.3160, -2.1152],
        [ 0.3223, -1.2633,  0.3500,  0.3081],
        [ 0.1198,  1.2377,  1.1168, -0.2473]])
b:
 tensor([[-0.7193],
        [-0.4033],
        [-0.5966],
        [ 0.1820]])
x:
 tensor([[ 0.0363],
        [ 0.4987],
        [-0.3020],
        [ 0.4135]])

Check to see if $\mathbf{x}$ satisfies the equation

In [14]:
print(torch.mm(A,x))
tensor([[-0.7193],
        [-0.4033],
        [-0.5966],
        [ 0.1820]])