I have written linear regression code with cost function and the gradient descent. The code works well but the plot is wrong. I think that the source of the problem is temp value but I could not reach to the solution. The red plot should be like blue one but different angle.
Main Code :
clear; clc;
data = load('data.txt');
X = data(:,2:5); % Examples
y = data(:,1); % Number of weekly riders
% Feature Scaling
X(:,1) = (X(:,1)./(max(X(:,1))));
X(:,2) = (X(:,2)./(max(X(:,2))));
X(:,3) = (X(:,3)./(max(X(:,3))));
X(:,4) = (X(:,4)./(max(X(:,4))));
y(:,1) = (y(:,1)./(max(y(:,1))));
m = length(y);
theta = zeros(5,1);
iterations = 600; % Iteration for gradient descent
alpha = [0.01, 0.03]; % Learning rate
X = [ones(m,1) X];
J = CostF (X, y, theta); % Cost Function
[theta, J_history] = GradD (X, y, theta, alpha, iterations); % Gradient Descent Calculation
legend('0.01','0.03')
xlabel('Iteration Number')
GradD code
function [theta, J_history] = GradD (X, y, theta, alpha, iterations)
m = length(y); % Number of training examples
J_history = zeros(iterations, 1);
thetaLen = length(theta);
tempVal = theta; % Temporary variable to keep theta values
alpha = [0.01, 0.03];
for k = 1:length(alpha)
for iter = 1:iterations
temp = (X*theta - y);
for i = 1:thetaLen
tempVal(i,1) = sum(temp.*X(:,i));
end
end
theta = theta - (alpha(k)/m)*tempVal;
J_history(iter,1) = CostF(X,y,theta);
end
plot(J_history,'LineWidth', 2); grid on
hold on
end
CostF code
function J = CostF (X, y, theta)
m = length(y);
% Cost
J = (1/(2*m))*sum((X*theta - y).^2);
end

댓글 수: 2

madhan ravi
madhan ravi 2018년 11월 22일
you forgot to upload yur text file
Berkcan Oz
Berkcan Oz 2018년 11월 22일
Sorry for my mistake. I am adding the data file.
192000 15 1800000 5800 50
190400 15 1790000 6200 50
191200 15 1780000 6400 60
177600 25 1778000 6500 60
176800 25 1750000 6550 60
152800 63 1610000 16200 200
180800 25 1725000 8200 75
175200 30 1725000 8600 75
174400 30 1720000 8800 75
173920 30 1705000 9200 80
172800 30 1710000 9630 80
163200 40 1700000 10570 80
161600 40 1695000 11330 85
151680 77 1600000 16000 190
160800 40 1690000 11800 105
159200 40 1630000 11830 105
148800 65 1640000 12650 105
115696 102 1635000 13000 110
147200 75 1630000 13224 125
150400 75 1620000 13766 130
152000 75 1615000 14010 150
136000 80 1605000 14468 155
126240 86 1590000 15000 165

댓글을 달려면 로그인하십시오.

답변 (1개)

Berkcan Oz
Berkcan Oz 2018년 11월 24일

0 개 추천

Can anybody help me please about that ?

카테고리

도움말 센터File Exchange에서 Spline Postprocessing에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2018년 11월 22일

답변:

2018년 11월 24일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by