Skip to content

Commit 63bd2bd

Browse files
authored
Add files via upload
1 parent ffd2bd0 commit 63bd2bd

3 files changed

Lines changed: 146 additions & 0 deletions

File tree

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
% Assignment#1 - Machine Learning
2+
% Name: Yildirim Kocoglu
3+
4+
% Clear and close all
5+
clear;
6+
clc;
7+
close all;
8+
9+
% Load the data
10+
Data = xlsread('C:\Users\ykocoglu\Desktop\Classes\ML TTU\PROJ1\proj1Dataset.xlsx', 1, 'A2:B407'); % Please change the directory path (if needed)
11+
12+
% Delete any "Nan rows" (Missing Data)
13+
Data(any(isnan(Data), 2), :) = [];
14+
15+
% Seperate the Data into x (features - Weight) and y (realizations - Horsepower)
16+
x = Data(:,1);
17+
y = Data(:,2);
18+
19+
% Plot the scatter plot of x vs y
20+
figure(1)
21+
scatter(x,y,50,'x','r','LineWidth',2);
22+
title('Matlab''s "carbig" dataset');
23+
xlabel('Weight');
24+
ylabel('Horsepower');
25+
hold on;
26+
%% Analytical solution
27+
28+
29+
x = [Data(:,1), ones(size(Data,1),1)];
30+
31+
% Analytical solution - equation
32+
w = pinv(x'*x)*x'*y;
33+
y1 = x*w;
34+
35+
% Cost function from analytical solution
36+
JJ = sum((y - y1).^2);
37+
38+
% Plot the analytical solution line on the scatter plot
39+
40+
p = plot(x(:,1),y1, 'LineWidth',2, 'color', 'b');
41+
legend(p,'Closed form')
42+
hold off;
43+
44+
%% Gradient Descent solution
45+
46+
% Set learning rate (rho) - CAN BE ADJUSTED!
47+
rho = 0.001;
48+
49+
% Set Random initial guess between 0 and 1 for weights (changes at each run!)
50+
w2 = rand(2,1);
51+
52+
53+
% Initialize niter to keep track in the while loop
54+
niter = 0;
55+
56+
% Initialize Cost function (J) to monitor
57+
J = zeros(niter,1);
58+
w_matrix = zeros(size(w2,1),niter);
59+
60+
% Normalize the data
61+
xnorm = (x(:,1)-mean(x(:,1)))/std(x(:,1));
62+
63+
% Add 1 vector to xnorm for bias
64+
xnorm = [xnorm,ones(size(xnorm,1),1)];
65+
66+
% Set initial gradient_norm and tolerance in the following scale:
67+
% gradient_norm > tolerance (To avoid issues within the while loop) - CAN BE ADJUSTED!
68+
gradient_norm = 1;
69+
tolerance = 1*10^-1;
70+
71+
% Set maximum number of iterations for the while loop - CAN BE ADJUSTED!
72+
max_iter = 10000;
73+
74+
% GRADIENT DESCENT ALGORITHM!
75+
while gradient_norm > tolerance
76+
77+
% Store the weights (w)
78+
w_matrix(:,niter+1) = w2;
79+
gradient = (2.*w2'*(xnorm'*xnorm) - 2.*y'*xnorm);
80+
w2 = w2 - rho.*gradient';
81+
82+
% Store Cost function (J)
83+
y2 = xnorm*w2;
84+
J(niter+1) = sum((y - y2).^2);
85+
86+
% Keep track of number of iterations
87+
niter = niter + 1;
88+
89+
% STOPPING CRITERIA (If gradient <= tolerance or iterations >= 10000)
90+
91+
gradient_norm = norm(gradient); % Break out of while loop if gradient_norm < tolerance
92+
93+
if niter >= max_iter
94+
fprintf('Gradient Descent could not converge within max_iter: %d \n\nTry to adjust the following parameters in the following order:\n1) rho\n2) max_iter\n3) tolerance ( < initial gradient_norm)\n\nTERMINATING THE PROGRAM!\n', max_iter)
95+
break; % Break out of while loop
96+
97+
elseif any(isnan(w2)) % If any of the weights become 'NaN' at any iteration
98+
fprintf('Gradient Descent could not converge due to NaN values in w2 @ niter = %d \n\nTry to adjust the following parameters in the following order:\n1) rho\n2) max_iter\n3) tolerance ( < initial gradient_norm)\n\nTERMINATING THE PROGRAM!\n',niter)
99+
break; % Break out of while loop
100+
end
101+
102+
end % End of while loop
103+
104+
% Printf number of iterations it took to converge (gradient descent)
105+
if niter < max_iter && ~any(isnan(w2))
106+
fprintf('Number of iterations: %d\n', niter)
107+
end
108+
109+
% Convert weights obtained from gradient descent with normalized data to
110+
% fit the un-normalized data (Not sure if necessary!)
111+
w2 = x\(xnorm*w2);
112+
y3 = x*w2;
113+
114+
% Plot Gradient Descent solution line on the scatter plot of data
115+
figure(2)
116+
x = Data(:,1);
117+
y = Data(:,2);
118+
scatter(x,y,50,'x','r','LineWidth',2);
119+
title('Matlab''s "carbig" dataset');
120+
xlabel('Weight');
121+
ylabel('Horsepower');
122+
hold on;
123+
p5 = plot(x(:,1),y3, 'LineWidth',2, 'color', 'g');
124+
legend(p5,'Gradient Descent')
125+
hold off;
126+
127+
% Plot & Monitor the Cost function (J) (OPTIONAL!)
128+
129+
option = 'on'; % Choose 'on' or 'off' to turn on\off plot - CAN BE ADJUSTED!
130+
131+
if strcmp(option, 'on')
132+
figure(3)
133+
title('OPTIONAL PLOT: J(w) vs niter');
134+
xlabel('niter');
135+
ylabel('J(w)');
136+
hold on
137+
p2 = plot(1:niter,J, 'LineWidth',3, 'color', 'b');
138+
p3 = scatter(1,JJ,'x','g','LineWidth',10);
139+
p4 = scatter(niter,J(:,niter),'x','r','LineWidth',10);
140+
legend([p2, p3, p4],'Gradient Descent J(w)', 'Analytical solution optimum J(w)', 'Gradient Descent optimum J(w)')
141+
hold off
142+
elseif strcmp(option, 'off')
143+
fprintf('J(w) vs niter is not plotted\nChange option to plot!\n');
144+
else
145+
error('Please choose "on" or "off" to turn on/off plot. CHECK THE SPELLING!');
146+
end

PROJ1/Proj1.pdf

245 KB
Binary file not shown.

PROJ1/proj1Dataset.xlsx

16 KB
Binary file not shown.

0 commit comments

Comments
 (0)