coursera第二周

本文通过一个简单的线性回归实例,介绍了如何使用梯度下降法求解最佳参数θ的过程。从数据加载到梯度下降算法实现,再到最终的模型评估及预测,详细展示了机器学习中基本算法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值