function [theta, J_history] = gradient_descent(x, y, theta, alpha, num_iters) % Gradient descent function m = length(y); J_history = zeros(num_iters, 1); theta_save = theta;
for i = 1:num_iters % Be sure to update at the same time theta(1) = theta(1) - alpha / m * sum(x * theta_save - y); theta(2) = theta(2) - alpha / m * sum((x * theta_save - y) .* x(:,2)); theta_save = theta; J_history(i) = calc_costs(x, y, theta); endfor J_history endfunction
绘图函数(房价-面积数据)
1 2 3 4 5 6 7
function plot_data(x, y) plot(x, y, 'k.', 'MarkerSize', 10); ylabel('Profit in $10,000s'); xlabel('Population of City in 10,000s'); legend('Training data'); hold end
theta0_vals = linspace(-10, 10, 100); theta1_vals = linspace(-1, 4, 100); % initialize J_vals to a matrix of 0's J_vals = zeros(length(theta0_vals), length(theta1_vals)); %构造n*n的0矩阵 % Fill out J_vals for i = 1:length(theta0_vals) for j = 1:length(theta1_vals) t = [theta0_vals(i); theta1_vals(j)]; %构造列向量 J_vals(i,j) = calc_costs(X, y, t); end end