码迷,mamicode.com
首页 > 系统相关 > 详细

Machine Learning - week 2 - 编程

时间:2017-08-11 22:59:30      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:sub   高度   mat   alt   octave   --   img   span   put   

 

3. % J = COMPUTECOST(X, y, theta) computes the cost of using theta as the

% parameter for linear regression to fit the data points in X and y

 

传入的参数的 size 

size(X)

ans =

 

   m    n

 

octave:4> size(y)

ans =

 

   m    1

 

octave:5> size(theta)

ans =

 

   n   1

 

根据公式 

技术分享

hθ(x) = X * theta,size 为 m * 1。然后与 y 相减,再对所有元素取平方,之后求和。具体代码如下

function J = computeCost(X, y, theta)

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

J = 0;

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

end

gradientDescent  

 技术分享

i 表示的行数,j 表示的是列数。每列表示一个 feature。xj(i) 表示第 j 列第 i 个。如何用向量表示这个乘法?

首先,弄清楚 技术分享的意思。(对于每行 x 与对应的 y)预期值与真实值的差值 * 对应行的 x 的第 j 列个。j 与 θ 是对应的。下面是代码

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

m = length(y); % number of training examples
n = columns(X);
J_history = zeros(num_iters, 1);

for iter = 1:num_iters

    h = X * theta;

    for j = 1:n
        % 差值点乘    
        delta = alpha/m * sum(  (h - y) .* X(:, j));
        theta(j) = theta(j) - delta;
    end

    % Save the cost J in every iteration    
    J_history(iter) = computeCost(X, y, theta);

end

end
  

 点乘,对应元素相乘

[1; 2; 3] .* [2; 2; 2]
ans =

   2
   4
   6

 先弄清楚公式的意思,再寻找 Octave 中的表示方法。  

 

等高线图怎么看

这是练习脚本生成的等高线。

技术分享

同一条线、圆上的高度(y 值)是相同的,越密的地方变化越缓慢,反之变化越剧烈。

 

Machine Learning - week 2 - 编程

标签:sub   高度   mat   alt   octave   --   img   span   put   

原文地址:http://www.cnblogs.com/jay54520/p/7345915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!