Machine learning : Regression with one variable

学习NG的Machine Learning教程,先关推导及代码。由于在matleb或Octave中需要矩阵或向量,经常搞混淆,因此自己推导,并把向量的形式写出来了,主要包括cost function及gradient descent
见下图。
这里写图片描述

图中可见公式推导,及向量化表达形式的cost function(J).

这里写图片描述

图中为参数更新的向量化表达方式(其中有一处写错了,不想改了。。。)

下面regression with one variable的代码

% regression with one variable
data = load('dat.txt');
X = data(:,1); % X = m*1
y = data(:,2); % y = m*1

% plot data
plot(X,y);

X = [ones(m,1) X]; % X = m*2
theta = zeros(2,1); % theta = 2*1

%gradient descent
iterations = 1500;
alpha = 0.01;

fprintf('\nRunning Gradient Descent ...\n')
theta = gradientDescent(X, y, theta, alpha, iterations);

% print theta to screen
fprintf('Theta found by gradient descent:\n');
fprintf('%f\n', theta);

% 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

其中gradientDescent函数如下

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

%X: m*2 , y:m*1 , theta:2*1, alpha:1*1
for iter = 1:num_iters
    error = (X*theta - y); %m*1
    theta = theta - alpha/m*(X'*(X*theta-y)); 
    J_history(iter) = computeCost(X, y, theta);
end
plot([1:num_iters],J_history); %画图
pause;
end

其中computeCost代码如下

function J = computeCost(X, y, theta)

m = length(y); % number of training examples
J = 0;
error = X * theta - y; % m*1
J = 1/(2*m)*sum(error .^ 2);

end

下见linear regression 正则化的公式
这里写图片描述

为方便查找,下附公式原图,
这里写图片描述

这里写图片描述

以下为regularized linear regression

这里写图片描述

这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值