Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4455864
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: IT职场

2014-03-26 23:35:29

文章来源:http://blog.csdn.net/xiazdong/article/details/7950566
多元线性回归其实方法和单变量线性回归差不多,我们这里直接给出算法:

computeCostMulti函数

[plain] view plaincopy
  1. function J = computeCostMulti(X, y, theta)  
  2.   
  3.     m = length(y); % number of training examples  
  4.     J = 0;  
  5.     predictions = X * theta;  
  6.     J = 1/(2*m)*(predictions - y)' * (predictions - y);  
  7.   
  8. end  

gradientDescentMulti函数

[plain] view plaincopy
  1. function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)  
  2.   
  3.     m = length(y); % number of training examples  
  4.     J_history = zeros(num_iters, 1);  
  5.     feature_number = size(X,2);  
  6.     temp = zeros(feature_number,1);  
  7.     for iter = 1:num_iters  
  8.   
  9.         for i=1:feature_number  
  10.             temp(i) = theta(i) - (alpha / m) * sum((X * theta - y).* X(:,i));  
  11.         end  
  12.         for j=1:feature_number  
  13.             theta(j) = temp(j);  
  14.         end  
  15.        
  16.         J_history(iter) = computeCostMulti(X, y, theta);  
  17.   
  18.     end  
  19.   
  20. end  



但是其中还是有一些区别的,比如在开始梯度下降之前需要进行feature Scaling:

[plain] view plaincopy
  1. function [X_norm, mu, sigma] = featureNormalize(X)  
  2.   
  3.     X_norm = X;  
  4.     mu = zeros(1, size(X, 2));  
  5.     sigma = zeros(1, size(X, 2));  
  6.     mu = mean(X);  
  7.     sigma = std(X);  
  8.     for i=1:size(mu,2)  
  9.         X_norm(:,i) = (X(:,i).-mu(i))./sigma(i);  
  10.     end  
  11.   
  12. end  


Normal Equation算法的实现


[plain] view plaincopy
  1. function [theta] = normalEqn(X, y)  
  2.   
  3.     theta = zeros(size(X, 2), 1);  
  4.     theta = pinv(X'*X)*X'*y;  
  5.   
  6. end  
阅读(1661) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~