返回顶部
首页 > 资讯 > 数据库 >基于pytorch的PINN代码
  • 408
分享到

基于pytorch的PINN代码

pythondjangomysqlmemcached 2023-09-09 17:09:57 408人浏览 安东尼
摘要

import torchimport torch.autograd as autograd # computation graphfrom torch import Tensor # ten

import torchimport torch.autograd as autograd         # computation graphfrom torch import Tensor                  # tensor node in the computation graphimport torch.nn as nn                     # neural networksimport torch.optim as optim               # optimizers e.g. gradient descent, ADAM, etc.import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecfrom mpl_toolkits.axes_grid1 import make_axes_locatablefrom mpl_toolkits.mplot3D import Axes3Dimport matplotlib.tickerfrom sklearn.model_selection import train_test_splitimport numpy as npimport timefrom pyDOE import lhs         #Latin Hypercube Samplingimport scipy.io#Set default dtype to float32torch.set_default_dtype(torch.float)#PyTorch random number generatortorch.manual_seed(1234)# Random number generators in other librariesnp.random.seed(1234)# Device configurationdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')print(device)if device == 'cuda':    print(torch.cuda.get_device_name())steps=10000lr=1e-1lr1 = 0.001layers = np.array([2,20,20,20,20,20,20,20,20,1]) #8 hidden layers#Nu: Number of training points # Nf: Number of collocation points (Evaluate PDE)N_u = 100 #Total number of data points for 'u'N_f = 10000 #Total number of collocation pointsnu = 0.01/np.pi #diffusion coeficientepoches = 1000def plot3D(x,t,y):  x_plot =x.squeeze(1)  t_plot =t.squeeze(1)  X,T= torch.meshgrid(x_plot,t_plot)  F_xt = y  fig,ax=plt.subplots(1,1)  cp = ax.contourf(T,X, F_xt,20,cmap="rainbow")  fig.colorbar(cp) # Add a colorbar to a plot  ax.set_title('F(x,t)')  ax.set_xlabel('t')  ax.set_ylabel('x')  plt.show()  ax = plt.axes(projection='3d')  ax.plot_surface(T.numpy(), X.numpy(), F_xt.numpy(),cmap="rainbow")  ax.set_xlabel('t')  ax.set_ylabel('x')  ax.set_zlabel('f(x,t)')  plt.show()def plot3D_Matrix(x, t, y):  X, T = x, t  F_xt = y  fig, ax = plt.subplots(1, 1)  cp = ax.contourf(T, X, F_xt, 20, cmap="rainbow")  fig.colorbar(cp)  # Add a colorbar to a plot  ax.set_title('F(x,t)')  ax.set_xlabel('t')  ax.set_ylabel('x')  plt.show()  ax = plt.axes(projection='3d')  ax.plot_surface(T.numpy(), X.numpy(), F_xt.numpy(), cmap="rainbow")  ax.set_xlabel('t')  ax.set_ylabel('x')  ax.set_zlabel('f(x,t)')  plt.show()def solutionplot(u_pred, X_u_train, u_train):    # https://GitHub.com/omniscientoctopus/Physics-InfORMed-Neural-Networks    fig, ax = plt.subplots()    ax.axis('off')    gs0 = gridspec.GridSpec(1, 2)    gs0.update(top=1 - 0.06, bottom=1 - 1 / 3, left=0.15, right=0.85, wspace=0)    ax = plt.subplot(gs0[:, :])    h = ax.imshow(u_pred, interpolation='nearest', cmap='rainbow',                  extent=[T.min(), T.max(), X.min(), X.max()],                  origin='lower', aspect='auto')    divider = make_axes_locatable(ax)    cax = divider.append_axes("right", size="5%", pad=0.05)    fig.colorbar(h, cax=cax)    ax.plot(X_u_train[:, 1], X_u_train[:, 0], 'kx', label='Data (%d points)' % (u_train.shape[0]), markersize=4,            clip_on=False)    line = np.linspace(x.min(), x.max(), 2)[:, None]    ax.plot(t[25] * np.ones((2, 1)), line, 'w-', linewidth=1)    ax.plot(t[50] * np.ones((2, 1)), line, 'w-', linewidth=1)    ax.plot(t[75] * np.ones((2, 1)), line, 'w-', linewidth=1)    ax.set_xlabel('$t$')    ax.set_ylabel('$x$')    ax.legend(frameon=False, loc='best')    ax.set_title('$u(x,t)$', fontsize=10)    '''     Slices of the solution at points t = 0.25, t = 0.50 and t = 0.75    '''    ####### Row 1: u(t,x) slices ##################    gs1 = gridspec.GridSpec(1, 3)    gs1.update(top=1 - 1 / 3, bottom=0, left=0.1, right=0.9, wspace=0.5)    ax = plt.subplot(gs1[0, 0])    ax.plot(x, usol.T[25, :], 'b-', linewidth=2, label='Exact')    ax.plot(x, u_pred.T[25, :], 'r--', linewidth=2, label='Prediction')    ax.set_xlabel('$x$')    ax.set_ylabel('$u(x,t)$')    ax.set_title('$t = 0.25s$', fontsize=10)    ax.axis('square')    ax.set_xlim([-1.1, 1.1])    ax.set_ylim([-1.1, 1.1])    ax = plt.subplot(gs1[0, 1])    ax.plot(x, usol.T[50, :], 'b-', linewidth=2, label='Exact')    ax.plot(x, u_pred.T[50, :], 'r--', linewidth=2, label='Prediction')    ax.set_xlabel('$x$')    ax.set_ylabel('$u(x,t)$')    ax.axis('square')    ax.set_xlim([-1.1, 1.1])    ax.set_ylim([-1.1, 1.1])    ax.set_title('$t = 0.50s$', fontsize=10)    ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35), ncol=5, frameon=False)    ax = plt.subplot(gs1[0, 2])    ax.plot(x, usol.T[75, :], 'b-', linewidth=2, label='Exact')    ax.plot(x, u_pred.T[75, :], 'r--', linewidth=2, label='Prediction')    ax.set_xlabel('$x$')    ax.set_ylabel('$u(x,t)$')    ax.axis('square')    ax.set_xlim([-1.1, 1.1])    ax.set_ylim([-1.1, 1.1])    ax.set_title('$t = 0.75s$', fontsize=10)    plt.savefig('Burgers.png', dpi=500)class FCN(nn.Module):    def __init__(self, layers):        super().__init__()  # call __init__ from parent class        'activation function'        self.activation = nn.Tanh()        'loss function'        self.loss_function = nn.MSELoss(reduction='mean')        'Initialise neural network as a list using nn.Modulelist'        self.linears = nn.ModuleList([nn.Linear(layers[i], layers[i + 1]) for i in range(len(layers) - 1)])        self.iter = 0        'Xavier Normal Initialization'        for i in range(len(layers) - 1):            nn.init.xavier_normal_(self.linears[i].weight.data, gain=1.0) #Xavier正态分布            wwww = self.linears[i].weight.data            # set biases to zero            nn.init.zeros_(self.linears[i].bias.data)    'foward pass'    def forward(self, x):        if torch.is_tensor(x) != True:            x = torch.from_numpy(x)        u_b = torch.from_numpy(ub).float().to(device)        l_b = torch.from_numpy(lb).float().to(device)        # preprocessing input        x = (x - l_b) / (u_b - l_b)  # feature scaling        # convert to float        a = x.float()        for i in range(len(layers) - 2):            z = self.linears[i](a)            a = self.activation(z)        a = self.linears[-1](a)        return a    def loss_BC(self, x, y):        loss_u = self.loss_function(self.forward(x), y)        return loss_u    def loss_PDE(self, X_train_Nf):        g = X_train_Nf.clone()        g.requires_grad = True        u = self.forward(g)        u_x_t = \        autograd.grad(u, g, torch.ones([X_train_Nf.shape[0], 1]).to(device), retain_graph=True, create_graph=True)[0]        u_xx_tt = autograd.grad(u_x_t, g, torch.ones(X_train_Nf.shape).to(device), create_graph=True)[0]        u_x = u_x_t[:, [0]]        u_t = u_x_t[:, [1]]        u_xx = u_xx_tt[:, [0]]        f = u_t + (self.forward(g)) * (u_x) - (nu) * u_xx        loss_f = self.loss_function(f, f_hat)        return loss_f    def loss(self, x, y, X_train_Nf):        loss_u = self.loss_BC(x, y)        loss_f = self.loss_PDE(X_train_Nf)        loss_val = loss_u + loss_f        return loss_val    'callable for optimizer'    def closure(self):        optimizer.zero_grad()        loss = self.loss(X_train_Nu, U_train_Nu, X_train_Nf)        print(loss)        loss.backward()        # self.iter += 1        #        # if self.iter % 100 == 0:        #     error_vec, _ = PINN.test()        #        #     print(loss, error_vec)        return loss    'test neural network'    def test(self):        u_pred = self.forward(X_test)        error_vec = torch.linalg.norm((u - u_pred), 2) / torch.linalg.norm(u, 2)  # Relative L2 Norm of the error (Vector)        u_pred = u_pred.cpu().detach().numpy()        u_pred = np.reshape(u_pred, (256, 100), order='F')        return error_vec, u_preddata = scipy.io.loadmat('./result/burgers_shock.mat')x = data['x']       # 256 points between -1 and 1 [256x1]t = data['t']       # 100 time points between 0 and 1 [100x1]usol = data['usol'] # solution of 256x100 grid pointsX, T = np.meshgrid(x,t)                         # makes 2 arrays X and T such that u(X[i],T[j])=usol[i][j] are a tupleplot3D(torch.from_numpy(x),torch.from_numpy(t),torch.from_numpy(usol)) #f_real was defined previously(function)print(x.shape,t.shape,usol.shape)print(X.shape,T.shape)X_test = np.hstack((X.flatten()[:,None], T.flatten()[:,None]))# Domain boundslb = X_test[0]  # [-1. 0.]ub = X_test[-1] # [1.  0.99]u_true = usol.flatten('F')[:,None] #Fortran style (Column Major)print(lb,ub)'''Boundary Conditions'''#Initial Condition -1 =< x =<1 and t = 0left_X = np.hstack((X[0,:][:,None], T[0,:][:,None])) #L1left_U = usol[:,0][:,None]#Boundary Condition x = -1 and 0 =< t =<1bottom_X = np.hstack((X[:,0][:,None], T[:,0][:,None])) #L2bottom_U = usol[-1,:][:,None]#Boundary Condition x = 1 and 0 =< t =<1top_X = np.hstack((X[:,-1][:,None], T[:,0][:,None])) #L3top_U = usol[0,:][:,None]X_train = np.vstack([left_X, bottom_X, top_X])U_train = np.vstack([left_U, bottom_U, top_U])#choose random N_u points for trainingidx = np.random.choice(X_train.shape[0], N_u, replace=False)X_train_Nu = X_train[idx, :] #choose indices from  set 'idx' (x,t)U_train_Nu = U_train[idx,:]      #choose corresponding u'''Collocation Points'''# Latin Hypercube sampling for collocation points# N_f sets of tuples(x,t)X_train_Nf = lb + (ub-lb)*lhs(2,N_f)X_train_Nf = np.vstack((X_train_Nf, X_train_Nu)) # append training points to collocation pointsprint("Original shapes for X and U:",X.shape,usol.shape)print("Boundary shapes for the edges:",left_X.shape,bottom_X.shape,top_X.shape)print("Available training data:",X_train.shape,U_train.shape)print("Final training data:",X_train_Nu.shape,U_train_Nu.shape)print("Total collocation points:",X_train_Nf.shape)'Convert to tensor and send to GPU'X_train_Nf = torch.Tensor(X_train_Nf).float().to(device)X_train_Nu = torch.Tensor(X_train_Nu).float().to(device)U_train_Nu = torch.from_numpy(U_train_Nu).float().to(device)X_test = torch.from_numpy(X_test).float().to(device)u = torch.from_numpy(u_true).float().to(device)f_hat = torch.zeros(X_train_Nf.shape[0], 1).to(device)PINN = FCN(layers)PINN.to(device)'Neural Network Summary'print(PINN)params = list(PINN.parameters())'''Optimization'''optimizer1 = torch.optim.Adam(PINN.parameters(), lr1)'L-BFGS Optimizer'optimizer = torch.optim.LBFGS(PINN.parameters(), lr,  max_iter=steps,  max_eval=None,  tolerance_grad=1e-11,  tolerance_change=1e-11,  history_size=100,  line_search_fn='strong_wolfe')for epoch in range(epoches):    optimizer1.zero_grad()    loss = loss = PINN.loss(X_train_Nu, U_train_Nu, X_train_Nf)    print("Adam loss:",loss)    loss.backward()    optimizer1.step()start_time = time.time()optimizer.step(PINN.closure)elapsed = time.time() - start_timeprint('Training time: %.2f' % (elapsed))''' Model Accuracy '''error_vec, u_pred = PINN.test()print('Test Error: %.5f' % (error_vec))solutionplot(u_pred,X_train_Nu.cpu().detach().numpy(),U_train_Nu)x1=X_test[:,0]t1=X_test[:,1]arr_x1=x1.reshape(shape=X.shape).transpose(1,0).detach().cpu()arr_T1=t1.reshape(shape=X.shape).transpose(1,0).detach().cpu()arr_y1=u_predarr_y_test=usolplot3D(torch.from_numpy(x),torch.from_numpy(t),torch.from_numpy(usol))

来源地址:https://blog.csdn.net/m0_45861823/article/details/128919362

您可能感兴趣的文档:

--结束END--

本文标题: 基于pytorch的PINN代码

本文链接: https://lsjlt.com/news/401743.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • 基于pytorch的PINN代码
    import torchimport torch.autograd as autograd # computation graphfrom torch import Tensor # ten...
    99+
    2023-09-09
    python django mysql memcached
  • 基于Pytorch实现的声音分类实例代码
    目录前言环境准备安装libsora安装PyAudio安装pydub训练分类模型生成数据列表训练预测其他总结前言 本章我们来介绍如何使用Pytorch训练一个区分不同音频的分类模型,例...
    99+
    2024-04-02
  • Pytorch实现GCN(基于PyTorch实现)
    文章目录 前言 一、导入相关库 二、加载Cora数据集 三、定义GCN网络 3.1 定义GCN层 3.1.1 邻接矩阵A 3.1...
    99+
    2023-09-06
    pytorch 深度学习 python 人工智能 神经网络
  • Pytorch实现GAT(基于PyTorch实现)
    文章目录 前言 一、导入相关库 二、加载Cora数据集 三、定义GAT网络 3.1 定义GAT层 3.1.1 将节点信息进行空间映射 ...
    99+
    2023-08-31
    pytorch 深度学习 python 人工智能 神经网络
  • Pytorch实现EdgeCNN(基于PyTorch实现)
    文章目录 前言 一、导入相关库 二、加载Cora数据集 三、定义EdgeCNN网络 3.1 定义EdgeConv层 3.1.1 特征拼接 ...
    99+
    2023-09-01
    pytorch 深度学习 python 图神经网络 人工智能
  • 基于pytorch搭建多特征LSTM时间序列预测代码详细解读(附完整代码)
    文章目录 LSTM时间序列预测数据获取与预处理模型构建训练与测试 LSTM时间序列预测 对于LSTM神经网络的概念想必大家也是熟练掌握了,所以本文章不涉及对LSTM概念的解读,仅解释如...
    99+
    2023-09-02
    pytorch lstm python
  • 基于PyTorch如何实现EdgeCNN
    这篇文章主要讲解了“基于PyTorch如何实现EdgeCNN”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“基于PyTorch如何实现EdgeCNN”吧!一、导入相关库本项目是采用自己实现的E...
    99+
    2023-07-05
  • 基于Java实现扫码登录的示例代码
    目录基本介绍原理解析1. 身份认证机制2. 流程概述代码实现1. 环境准备2. 主要依赖3. 生成二维码4. 扫描二维码5. 确认登录6. PC 端轮询7. 拦截器配置效果演示1. ...
    99+
    2024-04-02
  • 基于Pytorch实现逻辑回归
    本文实例为大家分享了Pytorch实现逻辑回归的具体代码,供大家参考,具体内容如下 1.逻辑回归  线性回归表面上看是“回归问题”,实际上处理的问题...
    99+
    2024-04-02
  • 基于Redis分布式锁的实现代码
    概述 目前几乎很多大型网站及应用都是分布式部署的,分布式场景中的数据一致性问题一直是一个比较重要的话题。分布式的CAP理论告诉我们“任何一个分布式系统都无法同时满足一致性(Consistency)、可用性(...
    99+
    2024-04-02
  • 基于Redis延迟队列的实现代码
    使用场景 工作中大家往往会遇到类似的场景: 1.对于红包场景,账户 A 对账户 B 发出红包通常在 1 天后会自动归还到原账户。 2.对于实时支付场景,如果账户 A 对商户 S 付款...
    99+
    2024-04-02
  • 基于Cesium绘制栅栏的示例代码
    目录最终效果创建 dynamicWallMaterialProperty.js 文件网上的资料要不收费,要不代码不全,很多跟绘制墙体有关的案例要不缺放法要不干嘛的,我自己根据网上的方...
    99+
    2024-04-02
  • 基于Python绘制520表白代码
    目录一、绘制成品二、绘制代码1.导入库2.选择背景音乐3.绘制心的外轮廓4.填充心并写告白信5.画心动线一、绘制成品 二、绘制代码 实现本文效果的整体思路是:加载库—选...
    99+
    2024-04-02
  • Python基于Pytorch的特征图提取实例
    目录简述单个图片的提取神经网络的构建特征图的提取可视化展示完整代码总结简述 为了方便理解卷积神经网络的运行过程,需要对卷积神经网络的运行结果进行可视化的展示。 大致可分为如下步骤: ...
    99+
    2024-04-02
  • 基于Pytorch如何实现的声音分类
    今天小编给大家分享一下基于Pytorch如何实现的声音分类的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。环境准备主要介绍li...
    99+
    2023-07-02
  • pytorch实战7:手把手教你基于pytorch实现VGG16
    手把手教你基于pytorch实现VGG16(长文) 前言 ​ 最近在看经典的卷积网络架构,打算自己尝试复现一下,在此系列文章中,会参考很多文章,有些已经忘记了出处,所以就不贴链接了,希望大家理解...
    99+
    2023-09-06
    pytorch 深度学习 python
  • 初识Pytorch使用transforms的代码
    首先,这次讲解的tansforms功能,通俗地讲,类似于在计算机视觉流程里的图像预处理部分的数据增强。 transforms的原理: 说明:图片(输入)通过工具得到结果(输出),这个...
    99+
    2024-04-02
  • 基于Pytorch的神经网络之Regression的实现
    目录1.引言2.神经网络搭建2.1准备工作2.2搭建网络2.3训练网络3.效果4.完整代码1.引言 我们之前已经介绍了神经网络的基本知识,神经网络的主要作用就是预测与分类,现在让我们...
    99+
    2024-04-02
  • 基于mybatis的java代码生成存储过程
     问题:   项目中目前使用mybatis操作数据库,使用插件(mybatis-generator)自动生成代码,对于增改查,使用存储过程实现了一版本,方便使用。         insert代码生成器用法: insert_code_g...
    99+
    2020-03-08
    基于mybatis的java代码生成存储过程
  • 基于nodejs 的多页面爬虫实例代码
    前言 前端时间再回顾了一下node.js,于是顺势做了一个爬虫来加深自己对node的理解。 主要用的到是request,cheerio,async三个模块 request 用于请求地址和快速下载图片...
    99+
    2022-06-04
    爬虫 实例 多页
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作