Changing Rates Plot Problem
Mostrar comentarios más antiguos
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 comentarios
madhan ravi
el 22 de Nov. de 2018
you forgot to upload yur text file
Berkcan Oz
el 22 de Nov. de 2018
Respuestas (1)
Berkcan Oz
el 24 de Nov. de 2018
0 votos
Categorías
Más información sobre Spline Postprocessing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!