切换git用户重新进行项目首次归档

This commit is contained in:
2025-10-17 15:12:38 +08:00
parent c07dbb586d
commit b9cce1d733
71 changed files with 82326 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
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()}")

View File

@@ -0,0 +1,41 @@
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
np.random.seed(0)
x = np.random.rand(100, 1) * 10 # 生成100个在0到10之间的随机数
y = 3.5 * x + 2 + np.random.randn(100, 1) * 2 # 真实的线性关系加上一些噪声
# 将numpy数组转换为torch张量
x_tensor = torch.from_numpy(x).float()
y_tensor = torch.from_numpy(y).float()
model = nn.Linear(in_features=1, out_features=1, bias=True)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
epochs = 100
for epoch in range(epochs):
# 前向传播
outputs = model(x_tensor)
loss = criterion(outputs, y_tensor)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch + 1}/{epochs}], Loss: {loss.item():.4f}')
# 可视化原始数据和拟合结果
predicted = model(x_tensor).detach().numpy() # detach()用于从计算图中移除张量,避免未来的梯度计算干扰。
plt.scatter(x, y, label='Original data')
plt.plot(x, predicted, color='red', label='Fitted line')
plt.legend()
plt.show()

0
FC_ML_Linear/__init__.py Normal file
View File