数学建模基于matlab动画演示梯度下降仿真含Matlab源码 1541期

Posted 紫极神光

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数学建模基于matlab动画演示梯度下降仿真含Matlab源码 1541期相关的知识,希望对你有一定的参考价值。

一、获取代码方式

获取代码方式1:
完整代码已上传我的资源: 【数学建模】基于matlab动画演示梯度下降仿真【含Matlab源码 1541期】

获取代码方式2:
通过订阅紫极神光博客付费专栏,凭支付凭证,私信博主,可获得此代码。

备注:
订阅紫极神光博客付费专栏,可免费获得1份代码(有效期为订阅日起,三天内有效);

二、部分源代码

% Getting Started examples for animateGraDes
%        

% Example 1: Simplest
%--------------------
agd = animateGraDes();                          % instantiate
agd.funcStr='x^2+2*x*y+3*y^2+4*x+5*y+6';        % cost function is required
agd.animate();                                  % start

% Example 2:  Alpha overshooting
%-------------------------------
agd = animateGraDes();                          % instantiate
agd.funcStr='x^2+2*x*y+3*y^2+4*x+5*y+6';        % cost function is required
% other optional parameters
agd.alpha = 0.2;                                % big alpha
agd.drawContour = true;                         % contour plot
agd.animate(); 

% Example 3: saddle point
%------------------------
agd = animateGraDes();
agd.alpha=0.15;
agd.funcStr='x^4-2*x^2+y^2';                    % special function with saddle points
agd.startPoint=[1.5 1.5];                       % point not on the ridge
agd.drawContour=true;                           % draw contour. Set to false if want 3D instead

agd.xrange=-2:0.1:2;                            % xrange covers local min and start point
agd.yrange=-2:0.1:2;                            % yrange covers local min and start point
agd.animate();
classdef animateGraDes < handle
    
    
    properties (Access=public)
        funcStr;                % Function of x, y in String
        alpha;                  % alpha for gradient descent
        startPoint;             % start point for gradient descent
        maxStepCount;           % Stop after # steps even if min is smaller than threshold
        stopThreshold;          % when distance is smaller than this, stop
 
        xrange;                 % x range for showing funcStr
        yrange;                 % y range for showing funStr
        showAnnotation;         % show annotation or not

        drawContour;            % drawContour instead of 3D surface

        stepsPerSecond;         % advance # steps each second
        outfile;                % output an animation GIF if set to a filename
    end
    
    % private properties for internal use only
    properties (Access=private)
        func;                   % function handler of funcStr
        xPartial;               % x partial derivative of func
        yPartial;               % y partial derivative of func
    end

    methods(Access=public)
        function agd = animateGraDes()
            % set default values. User can overwrite after instantiation
            agd.stepsPerSecond = 5;
            agd.alpha = 0.1;
            agd.startPoint = [5 5];
            agd.xrange = -10:1:10;
            agd.yrange = -10:1:10;
            agd.maxStepCount = 100;
            agd.stopThreshold = 1E-10;
            agd.showAnnotation = true;
            agd.outfile = [];
        end

        function animate(obj)
            clf
            try
                obj.func = str2func(['@(x, y)' obj.funcStr]);
                symFunc = sym(obj.func);
                syms x y
           
                disp(ME);
                return;
            end
            pauseInSec = 1/obj.stepsPerSecond;
            [X, Y] = meshgrid(obj.xrange, obj.yrange);
            Z = obj.computeZ(X, Y);
            if obj.drawContour
                contour(X, Y, Z, 20);
            else
                surf(X,Y,Z);
                alpha 0.5
            end
            hold on
            xStart = obj.startPoint(1);
            yStart = obj.startPoint(2);

            if ~isempty(obj.outfile)
                [img, map] = rgb2ind(frame2im( getframe(gcf)),256);
                imwrite(img,map,obj.outfile,'gif','DelayTime',0.5);
            end
            ann = [];
            if obj.showAnnotation
                dim = [0.05 0.81 0.38 0.13];
                strDisplay = 'Running ...';
                ann = annotation('textbox', dim, 'String', strDisplay,'BackgroundColor','white', 'FitBoxToText','on');
            end
            for i=0:obj.maxStepCount
                zStart = obj.func(xStart, yStart);
                xEnd = double(xStart - obj.getXpartial(xStart, yStart));
                yEnd = double(yStart - obj.getYpartial(xStart, yStart));
                zEnd = double(obj.func(xEnd, yEnd));
                if obj.drawContour
                    plot([xStart xEnd], [yStart, yEnd], 'r-*');
                else
                    plot3([xStart xEnd], [yStart yEnd], [zStart zEnd],'r-*');
             
                end

                xStart = xEnd;
                yStart = yEnd;
                if ~isempty(obj.outfile)
                    [img, map] = rgb2ind(frame2im( getframe(gcf)),256);
                    imwrite(img,map,obj.outfile,'gif','writemode', 'append','delaytime',pauseInSec);
                else
                    pause(pauseInSec);
                end
                ann.String = ['Running '  num2str(i) '/' num2str(obj.maxStepCount)];
            end
            if obj.showAnnotation
                if ~isempty(ann)
                strDisplay = ['\\alpha: '  num2str(obj.alpha)], ...
                    ['step count: ' num2str(i)], ...
                    ['Min: (' num2str(xEnd) ', ' num2str(yEnd) ', ' num2str(zEnd) ')'];
                ann.String = strDisplay;
                end
            
                if ~isempty(obj.outfile)
                    [img, map] = rgb2ind(frame2im( getframe(gcf)),256);
                    imwrite(img,map,obj.outfile,'gif','writemode', 'append','delaytime',pauseInSec);
                end
            end
     
            x = xIn;
            y = yIn;
            zValue = obj.alpha*subs(obj.xPartial);
        end
        function Z = computeZ(obj, X, Y)
            sz = size(X);
            Z = zeros(sz(1), sz(2));

            for i=1:sz(1)
                for j=1:sz(2)
                    Z(i, j) = obj.func(X(i, j), Y(i, j));
                end
            end

        end
        function done = checkStop(obj, xStart, xEnd, yStart, yEnd, zStart, zEnd)
            done = false;
            dis = (xStart-xEnd)^2+(yStart-yEnd)^2+(zStart-zEnd)^2;
            if dis <obj.stopThreshold
                done = true;
            end
        end
    end
end

三、运行结果

四、matlab版本及参考文献

1 matlab版本
2014a

2 参考文献
[1]李昕.MATLAB数学建模[M].清华大学出版社.2017
[2]王健,赵国生.MATLAB数学建模与仿真[M].清华大学出版社.2016
[3]余胜威.MATLAB数学建模经典案例实战[M].清华大学出版社.2015

以上是关于数学建模基于matlab动画演示梯度下降仿真含Matlab源码 1541期的主要内容,如果未能解决你的问题,请参考以下文章

数学建模基于matlab动态水波仿真含Matlab源码 2056期

数学建模基于matlab动态水波仿真含Matlab源码 2056期

数学建模基于matlab GUI排队系统仿真含Matlab源码 1253期

数学建模基于matlab单列多服务台排队系统仿真含Matlab源码 1698期

数学建模基于matlab三维海浪模型仿真含Matlab源码 1159期

数学建模基于matlab GUI彩票仿真系统含Matlab源码 1501期