import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
# 定义一个简单的神经网络
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc = nn.Sequential(
nn.Linear(1, 10),
nn.ReLU(),
nn.Linear(10, 1)
)
def forward(self, x):
return self.fc(x)
# 定义损失函数和优化器
criterion = nn.MSELoss()
model = SimpleNN()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 生成一些训练数据,这里使用了一个简单的线性函数 y = 2x + 3 加上一些噪声
x_train = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y_train = 2 * x_train + 3 + 0.2 * torch.rand(x_train.size())
# 保存训练误差和步数
errors = []
# 开始训练
for epoch in range(1000):
output = model(x_train)
loss = criterion(output, y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
errors.append(loss.item())
if epoch % 100 == 0:
print(f'Epoch [{epoch}/1000] Loss: {loss.item():.4f}')
# 使用打靶法求解微分方程 y'' = -y
def shooting_method(x):
# 假设y(0)=1, y'(0)=0
# 实现欧拉法或者任何简单的步进方法
y0, y1 = 1.0, 0.0 # 初始条件
h = x[1] - x[0]
ys = [y0]
y = y0
for i in range(1, len(x)):
# 简单的打靶法步进
y_new = y + h * y1
y1 = y1 - h * y # 基于y''=-y
y = y_new
ys.append(y)
return np.array(ys)
# 定义 x 范围
x_vals = np.linspace(-1, 1, 100)
# 计算神经网络输出
with torch.no_grad():
y_nn = model(torch.Tensor(x_vals).unsqueeze(1)).squeeze().numpy()
# 计算打靶法的数值解
y_shoot = shooting_method(x_vals)
# 绘制误差变化
plt.figure()
plt.plot(errors)
plt.title('Training Error over Time')
plt.xlabel('Training Steps')
plt.ylabel('Error')
plt.savefig('training_error.png')
# 绘制数值解和神经网络解进行比较
plt.figure()
plt.plot(x_vals, y_nn, label='NN Solution')
plt.plot(x_vals, y_shoot, label='Shooting Method', linestyle='dashed')
plt.title('Comparison of Solutions')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.savefig('solution_comparison.png')
# 显示图像
plt.show()