PyTorch study notes[4]

文章目录

  • the system of equations
  • references

the system of equations

  1. the definition of matrix with mathematical form. PyTorch study notes[4]_第1张图片
  2. the following sample code expresses the maxtrix and square matrix.
import torch

# 从 Python 列表创建矩阵
matrix = torch.tensor([[1, 2, 3], 
                       [4, 5, 6]])
print(matrix)
# 方阵
matrix = torch.zeros(5,5)
matrix[2][1]=11
print(matrix)
PS E:\learn\learnpy> & D:/Python312/python.exe e:/learn/learnpy/learn1.py
tensor([[1, 2, 3],
        [4, 5, 6]])
tensor([[ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0., 11.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.]])
  1. A x = b Ax=b Ax=b
  • to solve the overdetermined system of equations is as follows:
import torch
# 超定方程组示例 (A 是 m×n, m > n)
A = torch.tensor([[1.5, 2.], [3.7, 4.], [5.8, 6.9]], dtype=torch.float32)
b = torch.tensor([3.8, 37.1, 11.9], dtype=torch.float32)

# 最小二乘解
x_lstsq = torch.linalg.lstsq(A, b).solution
print(x_lstsq)  # 输出最小二乘解

the least squares solution via torch.linalg.lstsq computation is a appropriate solving for the overdetermined system of equations or A is not invertible .

  • square matrix which is invertible
import torch

# 定义矩阵 A 和向量 b
A = torch.tensor([[2., 1.], [1., 3.]], dtype=torch.float32)
b = torch.tensor([5., 7.], dtype=torch.float32)

# 方法1:直接解线性方程组 (推荐)
x = torch.linalg.solve(A, b)
print(x)  # 输出解向量 x

# 方法2:通过逆矩阵计算 (数值稳定性较差,不推荐)
x_inv = torch.inverse(A) @ b
print(x_inv)
  • if matrix is complex matrix, you can still use such as torch.linalg.lstsq , torch.linalg.solve and so on.
import torch

# 构造复矩阵和向量
A = torch.complex(
    torch.tensor([[1.0, 2.0], [3.0, 4.0]]),
    torch.tensor([[0.5, 1.0], [1.5, 2.0]])
)
b = torch.complex(
    torch.tensor([1.0, 2.0]),
    torch.tensor([0.5, 1.0])
)

# 求解 Ax = b
x = torch.linalg.solve(A, b)
print("解 x:\n", x)

# 验证结果
print("验证 Ax - b:\n", A @ x - b)  # 应接近零

references

  1. deepseek
  2. 《矩阵分析与应用》

你可能感兴趣的:(PyTorch study notes[4])