目录
今天第一天接触PINN,用深度学习的方法求解PDE,看来是非常不错的方法。做了一个简单易懂的例子,这个例子非常适合初学者。做了一个小demo, 大家可以参考参考
所用工具
使用了python和pytorch进行实现
python3.6
toch1.10
数学方程
使用一个最简单的常微分方程:
f ′ ( x ) = f ( x ) ( 1 ) f ( 0 ) = 1 ( 2 ) f'(x) = f(x) \hspace{2cm}(1) \ f(0) = 1 \hspace{2.6cm}(2)f ′(x )=f (x )(1 )f (0 )=1 (2 )
这个微分方程其实就是:
f ( x ) = e x ( 3 ) f(x)=e^{x} \hspace{2.45cm}(3)f (x )=e x (3 )
模型搭建
核心-使用最简单的全连接层:
class Net(nn.Module):
def __init__(self, NL, NN):
super(Net, self).__init__()
self.input_layer = nn.Linear(1, NN)
self.hidden_layer = nn.linear(NN,int(NN/2))
self.output_layer = nn.Linear(int(NN/2), 1)
def forward(self, x):
out = torch.tanh(self.input_layer(x))
out = torch.tanh(self.hidden_layer(out))
out_final = self.output_layer(out)
return out_final
偏微分方程定义,也就是公式(1):
def ode_01(x,net):
y=net(x)
y_x = autograd.grad(y, x,grad_outputs=torch.ones_like(net(x)),create_graph=True)[0]
return y-y_x
所有实现代码
一下代码复制粘贴,可直接运行:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from torch import autograd
"""
用神经网络模拟微分方程,f(x)'=f(x),初始条件f(0) = 1
"""
class Net(nn.Module):
def __init__(self, NL, NN):
super(Net, self).__init__()
self.input_layer = nn.Linear(1, NN)
self.hidden_layer = nn.Linear(NN,int(NN/2))
self.output_layer = nn.Linear(int(NN/2), 1)
def forward(self, x):
out = torch.tanh(self.input_layer(x))
out = torch.tanh(self.hidden_layer(out))
out_final = self.output_layer(out)
return out_final
net=Net(4,20)
mse_cost_function = torch.nn.MSELoss(reduction='mean')
optimizer = torch.optim.Adam(net.parameters(),lr=1e-4)
def ode_01(x,net):
y=net(x)
y_x = autograd.grad(y, x,grad_outputs=torch.ones_like(net(x)),create_graph=True)[0]
return y-y_x
plt.ion()
iterations=200000
for epoch in range(iterations):
optimizer.zero_grad()
x_0 = torch.zeros(2000, 1)
y_0 = net(x_0)
mse_i = mse_cost_function(y_0, torch.ones(2000, 1))
x_in = np.random.uniform(low=0.0, high=2.0, size=(2000, 1))
pt_x_in = autograd.Variable(torch.from_numpy(x_in).float(), requires_grad=True)
pt_y_colection=ode_01(pt_x_in,net)
pt_all_zeros= autograd.Variable(torch.from_numpy(np.zeros((2000,1))).float(), requires_grad=False)
mse_f=mse_cost_function(pt_y_colection, pt_all_zeros)
loss = mse_i + mse_f
loss.backward()
optimizer.step()
if epoch%1000==0:
y = torch.exp(pt_x_in)
y_train0 = net(pt_x_in)
print(epoch, "Traning Loss:", loss.data)
print(f'times {epoch} - loss: {loss.item()} - y_0: {y_0}')
plt.cla()
plt.scatter(pt_x_in.detach().numpy(), y.detach().numpy())
plt.scatter(pt_x_in.detach().numpy(), y_train0.detach().numpy(),c='red')
plt.pause(0.1)
结果展示
训练0次时的结果也就是没训练,蓝色是真实值、红色是预测值:
训练2000次时的结果,蓝色是真实值、红色是预测值:
训练7000次和13000时的结果,蓝色是真实值、红色是预测值:
训练20000时的结果,蓝色是真实值、红色是预测值,不过红色已经完全把蓝色覆盖了,也就是完全拟合了:
; 参考文献
[1]. 每天进步一点点吧. PINN学习记录.
https://blog.csdn.net/weixin_45805559/article/details/121574293
Original: https://blog.csdn.net/qq_24211837/article/details/124383808
Author: 刘文凯
Title: PINN学习与实验(一)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/729131/
转载文章受原作者版权保护。转载请注明原作者出处!