Cost Vs Number of Iterations in Gradient Descent | MATLAB
Prerequisite:
Join us on Telegram:
https://t.me/matlabirawen
Join us on Facebook Group: https://www.facebook.com/groups/matlabcodes
%Code:
clc
clear all
close all
format long
figure;
x=[1,2,3,4,5];
y=[5,7,9,11,13];
m=0;
c=0;
slope=[];
plot(x,y,'bo','linewidth',3);
hold on;
axis([-1 10 0 15]);
cost=[];
intercept=[];
for
h=1:10000
predicted=m*x+c;
s=y-predicted;
w=((sum(-2*x.*s))/length(x))*0.08;
m=m-w;
slope=[slope m];
w=((sum(-2*s))/length(x))*0.08;
c=c-w;
intercept=[intercept c];
e=m*x+c;
costa=(1/length(x))*sum(s.^2);
cost=[cost costa];
end
plot(x,m*x+c,'k','linewidth',3);
axis([-1 10 0 15]);
e=[slope' intercept' cost'];
figure;
h=1:10000;
plot(h(1:200),cost(1:200));
xlabel('Iteration');
ylabel('Cost
or mean square error');
title('Cost
Function');
Join us on Facebook Group: https://www.facebook.com/groups/matlabcodes
No comments