Coursera-机器学习(吴恩达)第二周-编程作业

这篇博客回顾了吴恩达的机器学习课程中的一元和多元线性回归编程作业。作者强调在编程前理解X、y、theta的矩阵维度,并详细介绍了每个步骤,包括一元线性回归的代价函数和梯度下降,以及多元线性回归的特征缩放、代价函数、梯度下降和正规方程。

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

已经学习吴恩达的机器学习四周,但对编程还是不够熟练,所以想重新总结一下自己的编程作业,加强巩固。

在写代码之前一定要搞清楚X、y、theta是几乘几的矩阵。

一元线性回归,步骤:

1、设置代价函数

2、梯度下降,对代价函数求θ的偏导,更新θ的值,迭代更新。

% 代价函数
function J = computeCost(X, y, theta)

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.

% ------ my first try ----------
% 使用迭代的方法计算
% for i = 1 : m
	% J = J + ((theta(1) + X(i, 2) * theta(2)) - y(i))^2;
% endfor

% J = J / 2 / m;
% ------------------------------

% ------ my second try ---------
% 使用向量化计算

J = sum((X * theta - y) .^ 2) / 2 / m;

% ------------------------------

% =========================================================================

end
% 梯度下降
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
%   theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by 
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值