1、进行了一次初始化,清除掉了所有的残留数据,保证在运行时不会受到额外的干扰
clear ; close all; clc
2、输出两行字
fprintf('Running warmUpExercise ... \n');
fprintf('5x5 Identity Matrix: \n');
调用warmUpExercise()方法,输出一个5*5的矩阵,在输出完毕后暂停
warmUpExercise()
fprintf('Program paused. Press enter to continue.\n');
pause;
3、把ex1data1.txt中的数据载入进去
fprintf('Plotting Data ...\n')
data = load('ex1data1.txt');
把第一列的所有数据赋给X,第二列的所有数据赋给y,用m统计y的长度
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples
可视化数据
plotData(X, y);
plotData方法代码如下:
figure; % open a new figure window
plot(x,y,'rx','MarkerSize',10);
xlabel('Profit in $10,000s');
ylabel('Population of City in 10,000s');
fprintf('Program paused. Press enter to continue.\n');
pause;
4、进行梯度下降算法
在X的前面加一列,并初始化theta
X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters
填写初始化次数和学习率
iterations = 1500;
alpha = 0.01;
计算代价函数
computeCost(X, y, theta)
函数如下:
m = length(y); % number of training examples
J = sum((X * theta - y).^2)/(2*m);
运行梯度下降
theta = gradientDescent(X, y, theta, alpha, iterations);
函数如下:
% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
theta_new = theta;
n = length(theta);
for iter = 1:num_iters
for j = 1:n
theta_new(j) = theta(j) - (alpha/m) * sum((X * theta - y).* X(:,j));
end
theta = theta_new;
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
5、输出此时的theta
% print theta to screen
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));
6、画出拟合曲线
% Plot the linear fit
hold on; % keep previous plot visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % don't overlay any more plots on this figure
7、输出预测值
% Predict values for population sizes of 35,000 and 70,000
predict1 = [1, 3.5] *theta;
fprintf('For population = 35,000, we predict a profit of %f\n',...
predict1*10000);
predict2 = [1, 7] * theta;
fprintf('For population = 70,000, we predict a profit of %f\n',...
predict2*10000);
fprintf('Program paused. Press enter to continue.\n');
pause;