1.背景
python使用pytorch构建神经网络,利用神经网络生成曲线,这篇文章旨在构建使用神经网络构成的曲线进行积分微分计算。
项目背景:使用神经网络构建一个速度曲线,速度曲线积分是路程,微分是加速度,要求积分路径是一个定值。
2.代码
1.神经网络构建部分
class IntegralNetwork(nn.Module):
def __init__(self):
super(IntegralNetwork, self).__init__()
self.fc1 = nn.Linear(1, 256)
self.fc2 = nn.Linear(256, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
integral_model = IntegralNetwork()
integral_optimizer = optim.Adam(integral_model.parameters(), lr=0.01)
2.导数计算
# 计算曲线在每个点的导数
accelerate = torch.autograd.grad(y_integral, x, torch.ones_like(y_integral), create_graph=True, allow_unused=True)[0]
3.积分部分
integral_approx = torch.trapz(y_integral.squeeze(), x.squeeze())
完整代码
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
max_accelerate = 0.2
targetvalue = 0.1
#积分网络
class IntegralNetwork(nn.Module):
def __init__(self):
super(IntegralNetwork, self).__init__()
self.fc1 = nn.Linear(1, 256)
self.fc2 = nn.Linear(256, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
integral_model = IntegralNetwork()
integral_optimizer = optim.Adam(integral_model.parameters(), lr=0.01)
def generate_velocitynetwork(target_integral,max_accelerate):
# 训练循环,使生成的曲线的积分接近目标积分
for epoch in range(1000):
integral_optimizer.zero_grad()
# 生成输入数据
x = torch.linspace(0, 1, 100).unsqueeze(1)
# 进行积分计算
y_integral = integral_model(x)
integral_approx = torch.trapz(y_integral.squeeze(), x.squeeze())
# 确保 x 和 y_integral 都需要梯度
x.requires_grad_(True)
y_integral.requires_grad_(True)
# 计算曲线在每个点的导数
accelerate = torch.autograd.grad(y_integral, x, torch.ones_like(y_integral), create_graph=True, allow_unused=True)[0]
# 确保 x 和 y_integral 都需要梯度
x.requires_grad_(True)
y_integral.requires_grad_(True)
# 计算积分损失
integral_loss = torch.pow(integral_approx - target_integral, 2)
# 执行反向传播和优化步骤
integral_loss.backward()
integral_optimizer.step()
if epoch % 100 == 0:
print(f"Epoch [{epoch + 1}/1000], Integral Loss: {integral_loss.item()}")
generate_velocitynetwork(targetvalue,max_accelerate)
optimizer = optim.Adam(integral_model.parameters(), lr=0.01)
# 生成并绘制曲线
x_values = np.linspace(0, 1, 100)
velocity = integral_model(torch.Tensor(x_values).unsqueeze(1)).detach().numpy()
# 计算曲线的导数(微分)
x_tensor = torch.Tensor(x_values).unsqueeze(1)
x_tensor.requires_grad_(True)
integral_model(x_tensor).requires_grad_(True)
accelerate = torch.autograd.grad(integral_model(x_tensor), x_tensor, torch.ones_like(integral_model(x_tensor)), create_graph=True, allow_unused=True)[0]
accelerate = accelerate.detach().numpy()
# 计算曲线的积分值
integral_values = [0]
cumulative_integral = 0.0
for i in range(len(x_values)-1):
x_tensor_partial = torch.linspace(0, x_values[i+1], i + 2).unsqueeze(1)
y_integral_partial = integral_model(x_tensor_partial)
cumulative_integral = torch.trapz(y_integral_partial.squeeze(), x_tensor_partial.squeeze())
integral_values.append(cumulative_integral)
integral_values_tensor = torch.tensor(integral_values) # 转换为 PyTorch 张量
# 绘制曲线,速度曲线
plt.subplot(3, 1, 1)
plt.plot(x_values, velocity)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Generated Curve')
# 绘制微分,加速度曲线
plt.subplot(3, 1, 2)
plt.plot(x_values, accelerate)
plt.xlabel('x')
plt.ylabel('dy/dx')
plt.title('Derivative of Generated Curve')
# 绘制积分曲线,这个就是位置曲线
plt.subplot(3, 1, 3)
plt.plot(x_values, integral_values_tensor.detach().numpy())
plt.xlabel('x')
plt.ylabel('Integral')
plt.title('Integral Curve')
plt.axhline(y=targetvalue, color='r', linestyle='--', label='Target Integral')
plt.legend()
plt.tight_layout()
plt.show()
#神经网络生成三段曲线