Files
ModelTrainingPython/FC_ML_Linear/FC_ML_Least_Squares.py

9 lines
345 B
Python
Raw Permalink Normal View History

import torch
# 构建超定方程组 Ax=b (3方程2未知数)
A = torch.tensor([[2.0, 3], [1, 4], [3, 1]]) # 3x2矩阵
b = torch.tensor([5.0, 6, 4]).reshape(-1,1) # 3x1向量
# 解法1正规方程 (A^T A)^-1 A^T b
solution = torch.linalg.lstsq(A, b).solution # PyTorch内置最小二乘
print(f"最小二乘解:\n{solution.numpy()}")