Matlab 深度学习工具箱 案例学习与测试————求二阶微分方程

Matlab 复制代码
clc
clear

% 定义输入变量
x = linspace(0,2,10000)';

% 定义网络的层参数
inputSize = 1;
layers = [
    featureInputLayer(inputSize,Normalization="none")
    fullyConnectedLayer(10)
    sigmoidLayer
    fullyConnectedLayer(1)
    sigmoidLayer];
% 创建网络
net = dlnetwork(layers);

% 训练轮数
numEpochs = 15;
% 每个Batch的数据个数
miniBatchSize = 100;
Matlab 复制代码
% SGDM优化方法设置的参数
initialLearnRate = 0.5;
learnRateDropFactor = 0.5;
learnRateDropPeriod = 5;
momentum = 0.9;
velocity = [];
Matlab 复制代码
% 损失函数里面考虑初始条件的系数
icCoeff = 7;

% ArrayDatastore
ads = arrayDatastore(x,IterationDimension=1);
% 创建一个用于处理管理深度学习数据的对象
mbq = minibatchqueue(ads, ...
    MiniBatchSize=miniBatchSize, ...
    PartialMiniBatch="discard", ...
    MiniBatchFormat="BC");

% 用于迭代过程监控
numObservationsTrain = numel(x);
numIterationsPerEpoch = floor(numObservationsTrain / miniBatchSize);
numIterations = numEpochs * numIterationsPerEpoch;

% 创建监控对象 
% 由于计时器在您创建监控器对象时启动,因此请确保在靠近训练循环的位置创建对象。
monitor = trainingProgressMonitor( ...
    Metrics="LogLoss", ...
    Info=["Epoch" "LearnRate"], ...
    XLabel="Iteration");

% Train the network using a custom training loop
epoch = 0;
iteration = 0;
learnRate = initialLearnRate;
start = tic;

% Loop over epochs.
while epoch < numEpochs  && ~monitor.Stop
    epoch = epoch + 1;

    % Shuffle data,打乱数据.
    mbq.shuffle

    % Loop over mini-batches.
    while hasdata(mbq) && ~monitor.Stop

        iteration = iteration + 1;

        % Read mini-batch of data.
        X = next(mbq);

        % Evaluate the model gradients and loss using dlfeval and the modelLoss function.
        [loss,gradients] = dlfeval(@modelLoss, net, X, icCoeff);

        % Update network parameters using the SGDM optimizer.
        [net,velocity] = sgdmupdate(net,gradients,velocity,learnRate,momentum);

        % Update the training progress monitor.
        recordMetrics(monitor,iteration,LogLoss=log(loss));
        updateInfo(monitor,Epoch=epoch,LearnRate=learnRate);
        monitor.Progress = 100 * iteration/numIterations;

    end
    % Reduce the learning rate.
    if mod(epoch,learnRateDropPeriod)==0
        learnRate = learnRate*learnRateDropFactor;
    end
end


xTest = linspace(0,4,1000)';

yModel = minibatchpredict(net,xTest);

yAnalytic = exp(-xTest.^2);

figure;
plot(xTest,yAnalytic,"-")
hold on
plot(xTest,yModel,"--")
legend("Analytic","Model")

在深度学习中,被求导的对象(样本/输入)一般是多元的(向量x),绝大多数情况是标量y对向量x进行求导,很少向量y对向量x进行求导,否则就会得到复杂的微分矩阵。所以经常把一个样本看做一个整体,它包含多个变量(属性),对其所有属性求导后再加和,就得到了这个样本的偏导数之和。

Matlab 复制代码
% 损失函数
function [loss,gradients] = modelLoss(net, X, icCoeff)
    % 前向传播计算
    y = forward(net,X);
    
    % Evaluate the gradient of y with respect to x. 
    % Since another derivative will be taken, set EnableHigherDerivatives to true.
    dy = dlgradient(sum(y,"all"),X,EnableHigherDerivatives=true);
    
    % Define ODE loss.
    eq = dy + 2*y.*X;
    
    % Define initial condition loss.
    ic = forward(net,dlarray(0,"CB")) - 1;
    
    % Specify the loss as a weighted sum of the ODE loss and the initial condition loss.
    loss = mean(eq.^2,"all") + icCoeff * ic.^2;
    
    % Evaluate model gradients.
    gradients = dlgradient(loss, net.Learnables);

end
相关推荐
小陶的学习笔记23 分钟前
python~基础
开发语言·python·学习
学编程的闹钟26 分钟前
92【<h1-h6>指定文字大小】
学习
森之鸟29 分钟前
【我的经济学基础01-宏观经济】
学习
玄同76529 分钟前
Python 自动发送邮件实战:用 QQ/163 邮箱发送大模型生成的内容
开发语言·人工智能·python·深度学习·机器学习·邮件·邮箱
我的xiaodoujiao31 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 46--撰写 README项目说明文档文件
python·学习·测试工具·pytest
玄同76536 分钟前
机器学习中的三大距离度量:欧式距离、曼哈顿距离、切比雪夫距离详解
人工智能·深度学习·神经网络·目标检测·机器学习·自然语言处理·数据挖掘
第七序章36 分钟前
【Linux学习笔记】初识Linux —— 理解gcc编译器
linux·运维·服务器·开发语言·人工智能·笔记·学习
听麟44 分钟前
HarmonyOS 6.0+ APP AR文旅导览系统开发实战:空间定位与文物交互落地
人工智能·深度学习·华为·ar·wpf·harmonyos
学编程的闹钟1 小时前
99【html与php的混写】
学习
-Springer-1 小时前
STM32 学习 —— 个人学习笔记5(EXTI 外部中断 & 对射式红外传感器及旋转编码器计数)
笔记·stm32·学习