Generalized linear regression
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
function hypothesis = calculate_hypothesis(X, theta, training_example)
|
||||
%CALCULATE_HYPOTHESIS This calculates the hypothesis for a given X,
|
||||
%theta and specified training example
|
||||
x0 = X(training_example, 1);
|
||||
x1 = X(training_example, 2);
|
||||
x = X(training_example, 1:length(theta));
|
||||
|
||||
hypothesis = theta(1)*x0+theta(2)*x1;
|
||||
hypothesis = sum(x.*theta);
|
||||
%hypothesis = theta(1)*x0+theta(2)*x1+theta(3)*x2;
|
||||
end
|
||||
|
||||
|
||||
+6
-17
@@ -19,34 +19,23 @@ function theta = gradient_descent(X, y, theta, alpha, iterations, do_plot)
|
||||
% gradient descent
|
||||
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
||||
|
||||
theta_0 = theta(1);
|
||||
theta_1 = theta(2);
|
||||
|
||||
% fill temporary array with values of theta
|
||||
theta_temp = theta;
|
||||
for ind = 1:length(theta_temp)
|
||||
%update theta(1) and store in temporary variable theta_0
|
||||
sigma = 0.0;
|
||||
|
||||
for i = 1:m
|
||||
hypothesis = calculate_hypothesis(X, theta, i);
|
||||
output = y(i);
|
||||
sigma = sigma + (hypothesis - output);
|
||||
sigma = sigma + (hypothesis - output) * X(i, ind);
|
||||
end
|
||||
|
||||
theta_0 = theta_0 - ((alpha * 1.0) / m) * sigma;
|
||||
|
||||
|
||||
%update theta(2) and store in temporary variable theta_1
|
||||
sigma = 0.0;
|
||||
|
||||
for i = 1:m
|
||||
hypothesis = calculate_hypothesis(X, theta, i);
|
||||
output = y(i);
|
||||
sigma = sigma + (hypothesis - output) * X(i, 2);
|
||||
theta_temp(ind) = theta_temp(ind) - ((alpha * 1.0) / m) * sigma;
|
||||
end
|
||||
|
||||
theta_1 = theta_1 - ((alpha * 1.0) / m) * sigma;
|
||||
|
||||
%update theta
|
||||
theta = [theta_0, theta_1];
|
||||
theta = theta_temp;
|
||||
|
||||
%update cost_vector
|
||||
cost_vector = [cost_vector; compute_cost(X, y, theta)];
|
||||
|
||||
Reference in New Issue
Block a user