个人笔记-离散模型AMAW代码框架(改前)

2024-06-04 20:04

本文主要是介绍个人笔记-离散模型AMAW代码框架(改前),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

import需要用到的包

import os
import time
import numpy as np
import torch
from matplotlib import pyplot as plt, gridspec
from torch import nn
from torch.autograd import Variable
from tqdm import tqdm, trange
from pyDOE import lhs
# import h5py
# import scipy.io
import argparse

随机种子和指定GPU

os.environ['CUDA_VISIBLE_DEVICES'] = '0'
seed = 1234torch.set_default_dtype(torch.float)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)use_gpu = torch.cuda.is_available()
print('GPU:', use_gpu)

参数设置

parser = argparse.ArgumentParser()parser.add_argument('--hid_layers', help='number of hidden layers', type=int, default=6) 
parser.add_argument('--hid_neurons', help='number of neurons per layer', type=int, default=128)  
.
.
.
parser.add_argument('--adam_lr', help='learning rate of adam', type=float, default=0.001)
parser.add_argument('--lbfgs_lr', help='learning rate of lbfgs', type=float, default=0.5)
.
.
.

一些用到的函数

生成神经网络的结构

def generate_layers  # 如 [ 2 128 128 128 128 128 q+1]

生成随机内部点

def random_fun  # 随机生成可移动内部点,比如离散就随机生成维度为(1000,2)的内部点,而连续就是(1000,3)

数据格式转换

def is_cuda  # 将张量(Tensor)从CPU内存移动到GPU内存
def np_tensor  # 将传入的 data_var(预期是一个NumPy数组)转换为一个PyTorch张量(Tensor),并确保这个张量的数据类型是浮点数
def np_to_tensor_to_cuda   # 先把参数从numpy变成tensor再将Tensor从CPU内存移动到GPU内存

将两个 NumPy 数组(var1 和 var2)水平堆叠(hstack)在一起。这里的 order=‘F’ 表示以 Fortran 风格(即列优先)进行展平

def hstack_data(var1, var2):   var_hstack = np.hstack((var1.flatten(order='F')[:, None], var2.flatten(order='F')[:, None]))return var_hstack

在离散模型,这里说是(固定)内部点,其实是(固定)初值条件的点,直接生成coordinates的值就行,不用先生成index再转换到coordinates

def get_col_data(lb, ub, num_x, num_y)

生成固定的边界点

def get_bc_data(num_x, num_y, x, y)

生成测试用的数据集

def get_test_data(x, y)

生成训练/测试用的数据集

def data_generate(x, y, t, lb, ub, num_x, num_y):x_test = get_test_data(x, y)(xyt_b_bot_meshgrid_train, xyt_b_top_meshgrid_train, xyt_b_left_meshgrid_train,xyt_b_right_meshgrid_train) = get_bc_data(num_x, num_y, x, y)x_f_N = get_col_data(lb, ub, num_x, num_y)return (x_test, xyt_b_bot_meshgrid_train, xyt_b_top_meshgrid_train, xyt_b_left_meshgrid_train,xyt_b_right_meshgrid_train, x_f_N)

net的类

class Net(nn.Module):def __init__(self, layers):def forward(self, x):     

Model的类

初始化函数

def __init__

返回预测的所有结果(即离散模型就是q+1个u的值,而连续模型就是1个u的值)

    def train_U(self, x):return self.net(x)

预测的u,因为是离散模型,这里就只取h的值 (后期画图用)

    def predict_U(self, x):return self.train_U(x)[:, self.q:(self.q+1)]  # h

likelihood_loss

即take the negative logarithm of the likelihood function to get the negative log-likelihood as the desired loss function
L = e − s f ϕ L f ϕ + e − s f μ L f μ + e − s b ϕ L b ϕ + e − s b μ L b μ + s f ϕ + s f μ + s b ϕ + s b μ \begin{aligned} \mathcal{L}= & e^{-s_{f_{\phi}}} \mathcal{L}_{f_{\phi}}+e^{-s_{f_{\mu}}} \mathcal{L}_{f_{\mu}} \\ & +e^{-s_{b_{\phi}}} \mathcal{L}_{b_{\phi}}+e^{-s_{b_{\mu}}} \mathcal{L}_{b_{\mu}} \\ & + s_{f_{\phi}} + s_{f_{\mu}} + s_{b_{\phi}} + s_{b_{\mu}} \end{aligned} L=esfϕLfϕ+esfμLfμ+esbϕLbϕ+esbμLbμ+sfϕ+sfμ+sbϕ+sbμ

    def likelihood_loss(self, loss_f_h, loss_b_h, loss_f_mu, loss_b_mu):loss = (torch.exp(-self.x_f_s_h) * loss_f_h.detach() + self.x_f_s_h+ torch.exp(-self.x_b_s_h) * loss_b_h.detach() + self.x_b_s_h+ torch.exp(-self.x_f_s_mu) * loss_f_mu.detach() + self.x_f_s_mu+ torch.exp(-self.x_b_s_mu) * loss_b_mu.detach() + self.x_b_s_mu)return loss

true_loss

即比likelihood的loss少加自适应权重 s f ϕ + s f μ + s b ϕ + s b μ s_{f_{\phi}} + s_{f_{\mu}} + s_{b_{\phi}} + s_{b_{\mu}} sfϕ+sfμ+sbϕ+sbμ,loss function如下:
L = e − s f ϕ L f ϕ + e − s f μ L f μ + e − s b ϕ L b ϕ + e − s b μ L b μ \begin{aligned} \mathcal{L}= & e^{-s_{f_{\phi}}} \mathcal{L}_{f_{\phi}}+e^{-s_{f_{\mu}}} \mathcal{L}_{f_{\mu}} \\ & +e^{-s_{b_{\phi}}} \mathcal{L}_{b_{\phi}}+e^{-s_{b_{\mu}}} \mathcal{L}_{b_{\mu}} \end{aligned} L=esfϕLfϕ+esfμLfμ+esbϕLbϕ+esbμLbμ

    def true_loss(self, loss_f_h, loss_b_h, loss_f_mu, loss_b_mu):true_loss_value = (torch.exp(-self.x_f_s_h.detach()) * loss_f_h + torch.exp(-self.x_b_s_h.detach()) * loss_b_h+ torch.exp(-self.x_f_s_mu.detach()) * loss_f_mu + torch.exp(-self.x_b_s_mu.detach()) * loss_b_mu)return true_loss_value

对预测的边界点的q+1个u求出u_x,u_y (离散比连续的这一步复杂很多)

    def ub_x_h(self, boundary_data)def ub_y_h(self, boundary_data)def ub_x_mu(self, boundary_data)def ub_y_mu(self, boundary_data)

得到预测的边界点的q+1个u

 def get_b_pred(self, boundary_data)

定义正方形右边的公式(含theta_s)

可移动到Model的外面

    @staticmethoddef partial_derivative_phi(phi)

构造 L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ

这里只构造了边界的loss,内部点的在epoch_loss里面直接构造了

def loss_boundary_h(self)
def loss_boundary_mu(self)

画出离散型预测的u和U0的区别

这一步应该可以移到外面

def draw_loss_f(self, current_t_num, x_f, U00, U11)

生成 L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ(这一步在ADAM和LBFGS都会用到)

def epoch_loss(self)

LBFGS的loss

这里先跑一下epoch_loss得到 L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ,然后把 L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ当作true_loss的输入,得到 L = e − s f ϕ L f ϕ + e − s f μ L f μ + e − s b ϕ L b ϕ + e − s b μ L b μ \mathcal{L}= e^{-s_{f_{\phi}}} \mathcal{L}_{f_{\phi}}+e^{-s_{f_{\mu}}} \mathcal{L}_{f_{\mu}} +e^{-s_{b_{\phi}}} \mathcal{L}_{b_{\phi}}+e^{-s_{b_{\mu}}} \mathcal{L}_{b_{\mu}} L=esfϕLfϕ+esfμLfμ+esbϕLbϕ+esbμLbμ

def LBFGS_epoch_loss(self)

画预测的u

这一步应该可以移到外面

def draw_evaluate(self, x_test, pred, exact)

把一些可移动内部点移动到固定内部点

这一个看看能不能移动到Model的外面

def move_some_movable_points_to_fixed_points(self)

传统的PINN, AM的PINN, AM-AW的PINN

run_AM: 决定选点
run_AM_AW1:likelihood_loss在这,决定选点

AM-AW的具体步骤:
  1. 让自适应权重变成能够记录梯度属性的参数
    %%%%%%%%%%%%%%%%%%%%%%%%%

  2. 创建AM的for loop
    2.1 创建三个不同的优化器(L-BFGS的优化器,ADAM的优化器,自适应权重的优化器)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    2.2 创建一个ADAM的for loop
    2.2.1 通过epoch_loss得到 L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ
    -----------------------------------------------------------------------------
    2.2.2 optimizer_adam.zero_grad()
    2.2.3 通过true_loss( L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ)得 L = e − s f ϕ L f ϕ + e − s f μ L f μ + e − s b ϕ L b ϕ + e − s b μ L b μ \mathcal{L}= e^{-s_{f_{\phi}}} \mathcal{L}_{f_{\phi}}+e^{-s_{f_{\mu}}} \mathcal{L}_{f_{\mu}} +e^{-s_{b_{\phi}}} \mathcal{L}_{b_{\phi}}+e^{-s_{b_{\mu}}} \mathcal{L}_{b_{\mu}} L=esfϕLfϕ+esfμLfμ+esbϕLbϕ+esbμLbμ
    2.2.4 loss.backward()
    2.2.5 optimizer_adam.step()
    -------------------------------------------------------------------------------
    2.2.6 optimizer_adam_weight.zero_grad()
    2.2.7 通过likelihood_loss( L b ϕ \mathcal{L}_{b_{\phi}} Lbϕ, L b μ \mathcal{L}_{b_{\mu}} Lbμ, L f ϕ \mathcal{L}_{f_{\phi}} Lfϕ, L f μ \mathcal{L}_{f_{\mu}} Lfμ)得
    L = e − s f ϕ L f ϕ + e − s f μ L f μ + e − s b ϕ L b ϕ + e − s b μ L b μ + s f ϕ + s f μ + s b ϕ + s b μ \begin{aligned} \mathcal{L}= & e^{-s_{f_{\phi}}} \mathcal{L}_{f_{\phi}}+e^{-s_{f_{\mu}}} \mathcal{L}_{f_{\mu}} \\ & +e^{-s_{b_{\phi}}} \mathcal{L}_{b_{\phi}}+e^{-s_{b_{\mu}}} \mathcal{L}_{b_{\mu}} \\ & + s_{f_{\phi}} + s_{f_{\mu}} + s_{b_{\phi}} + s_{b_{\mu}} \end{aligned} L=esfϕLfϕ+esfμLfμ+esbϕLbϕ+esbμLbμ+sfϕ+sfμ+sbϕ+sbμ
    2.2.8 loss.backward()
    2.2.9 optimizer_adam_weight.step()
    (即后面继续回到第2.2步开始新的迭代直至达到adam_iter的数)

    2.3 打印 print(‘Adam done!’)

    2.4 self.optimizer_LBFGS.step(self.LBFGS_epoch_loss)
    2.5 打印 print(‘LBFGS done!’)

    2.6 根据p(x)改变可移动内部点
    (即后面继续回到第2步开始新的一轮)

def run_baseline(self)
def run_AM(self, current_t_num)
def run_AM_AW1(self, current_t_num)

train函数

这里生成可移动的内部点,定义自适应权重 s f ϕ s_{f_{\phi}} sfϕ, s b ϕ s_{b_{\phi}} sbϕ, s f μ s_{f_{\mu}} sfμ, s b μ s_{b_{\mu}} sbμ

def train(self, current_t_num)


又回到外面的一些函数

生成初值条件

def is_in_red_square(x_f)
def get_initial_h(x_f)

对内部点的u求导

def uf_x_h(h, col_pts)
def uf_y_h(h, col_pts)

IRK回溯回来的U0 (这里离散跟连续不一样)

def x_f_loss_fun_h(x_f, train_U)
def x_f_loss_fun_mu(x_f, train_U)

画图

def draw_exact_count(AM_count, current_t_num)
def draw_pred_q_count(AM_count, current_t_num)
def draw_pred_q_current(time_current)
def draw_pred_q()
def draw_current_exact(pic_num)
def draw_exact()
def draw_exact_points_count(AM_count, points, N_points=None, show_exact=False)
def draw_epoch_loss_count(AM_count, current_t_num)
def draw_exact_points_current(current_t_num, points, N_points=None, show_exact=False)
def draw_exact_points(points, N_points=None, show_exact=False)
def draw_epoch_loss_current(loss_current_num)
def draw_epoch_loss()
def draw_epoch_w()

定义不同case对应不同的上届和下界

def define_lb_ub(initial_condition_type)

main

参数,train

这篇关于个人笔记-离散模型AMAW代码框架(改前)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1030983

相关文章

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

AssetBundle学习笔记

AssetBundle是unity自定义的资源格式,通过调用引擎的资源打包接口对资源进行打包成.assetbundle格式的资源包。本文介绍了AssetBundle的生成,使用,加载,卸载以及Unity资源更新的一个基本步骤。 目录 1.定义: 2.AssetBundle的生成: 1)设置AssetBundle包的属性——通过编辑器界面 补充:分组策略 2)调用引擎接口API

一份LLM资源清单围观技术大佬的日常;手把手教你在美国搭建「百万卡」AI数据中心;为啥大模型做不好简单的数学计算? | ShowMeAI日报

👀日报&周刊合集 | 🎡ShowMeAI官网 | 🧡 点赞关注评论拜托啦! 1. 为啥大模型做不好简单的数学计算?从大模型高考数学成绩不及格说起 司南评测体系 OpenCompass 选取 7 个大模型 (6 个开源模型+ GPT-4o),组织参与了 2024 年高考「新课标I卷」的语文、数学、英语考试,然后由经验丰富的判卷老师评判得分。 结果如上图所

uniapp接入微信小程序原生代码配置方案(优化版)

uniapp项目需要把微信小程序原生语法的功能代码嵌套过来,无需把原生代码转换为uniapp,可以配置拷贝的方式集成过来 1、拷贝代码包到src目录 2、vue.config.js中配置原生代码包直接拷贝到编译目录中 3、pages.json中配置分包目录,原生入口组件的路径 4、manifest.json中配置分包,使用原生组件 5、需要把原生代码包里的页面修改成组件的方

公共筛选组件(二次封装antd)支持代码提示

如果项目是基于antd组件库为基础搭建,可使用此公共筛选组件 使用到的库 npm i antdnpm i lodash-esnpm i @types/lodash-es -D /components/CommonSearch index.tsx import React from 'react';import { Button, Card, Form } from 'antd'

《offer来了》第二章学习笔记

1.集合 Java四种集合:List、Queue、Set和Map 1.1.List:可重复 有序的Collection ArrayList: 基于数组实现,增删慢,查询快,线程不安全 Vector: 基于数组实现,增删慢,查询快,线程安全 LinkedList: 基于双向链实现,增删快,查询慢,线程不安全 1.2.Queue:队列 ArrayBlockingQueue:

17.用300行代码手写初体验Spring V1.0版本

1.1.课程目标 1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。 2、浓缩就是精华,用 300行最简洁的代码 提炼Spring的基本设计思想。 3、掌握Spring框架的基本脉络。 1.2.内容定位 1、 具有1年以上的SpringMVC使用经验。 2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。 3、 全程手写实现SpringM

大语言模型(LLMs)能够进行推理和规划吗?

大语言模型(LLMs),基本上是经过强化训练的 n-gram 模型,它们在网络规模的语言语料库(实际上,可以说是我们文明的知识库)上进行了训练,展现出了一种超乎预期的语言行为,引发了我们的广泛关注。从训练和操作的角度来看,LLMs 可以被认为是一种巨大的、非真实的记忆库,相当于为我们所有人提供了一个外部的系统 1(见图 1)。然而,它们表面上的多功能性让许多研究者好奇,这些模型是否也能在通常需要系

代码随想录算法训练营:12/60

非科班学习算法day12 | LeetCode150:逆波兰表达式 ,Leetcode239: 滑动窗口最大值  目录 介绍 一、基础概念补充: 1.c++字符串转为数字 1. std::stoi, std::stol, std::stoll, std::stoul, std::stoull(最常用) 2. std::stringstream 3. std::atoi, std

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共