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

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

在写代码之前一定要搞清楚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_iters, 1);

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta. 
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCost) and gradient here.
    %
	
    % ------------------------------------------------------------
    % 使用迭代的方法计算,速度很慢
	% d1 = 0;
	% d2 = 0;
	% for i = 1 : m
		% h = theta(1) + theta(2) * X(i, 2) - y(i);
		% d1 = d1 + h * X(i, 1);
		% d2 = d2 + h * X(i, 2);
	% endfor
	
	% theta(1) = theta(1) - alpha / m * d1;
	% theta(2) = theta(2) - alpha / m * d2;
    % ------------------------------------------------------------
    
    
        % 向量化计算
	theta = theta - alpha / m * (X' * (X * theta - y));


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

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

end

end

多元线性回归

1、特征缩放

2、代价函数

3、梯度下降

4、正规方程

如果使用向量化计算的话,多元线性回归的代价函数和梯度下降算法和一元线性回归一样。

% 特征缩放
function [X_norm, mu, sigma] = featureNormalize(X)
%FEATURENORMALIZE Normalizes the features in X 
%   FEATURENORMALIZE(X) returns a normalized version of X where
%   the mean value of each feature is 0 and the standard deviation
%   is 1. This is often a good preprocessing step to do when
%   working with learning algorithms.

% You need to set these values correctly
X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));

% ====================== YOUR CODE HERE ======================
% Instructions: First, for each feature dimension, compute the mean
%               of the feature and subtract it from the dataset,
%               storing the mean value in mu. Next, compute the 
%               standard deviation of each feature and divide
%               each feature by it's standard deviation, storing
%               the standard deviation in sigma. 
%
%               Note that X is a matrix where each column is a 
%               feature and each row is an example. You need 
%               to perform the normalization separately for 
%               each feature. 
%
% Hint: You might find the 'mean' and 'std' functions useful.
%       

mu = mean(X_norm);    % 求X_norm每列的均值,即每个特征的均值
sigma = std(X_norm);  % 标准差,std (X) = sqrt ( 1/(N-1) SUM_i (X(i) - mean(X))^2 )
                      % 求每列的标准差
X_norm = (X_norm - mu) ./ sigma;    % 注意"./"






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

end
function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(X, y, theta) computes the cost of using theta as the
%   parameter for linear regression to fit the data points in X and y

% 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.


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


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

end
function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
%GRADIENTDESCENTMULTI Performs gradient descent to learn theta
%   theta = GRADIENTDESCENTMULTI(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_iters, 1);

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta. 
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCostMulti) and gradient here.
    %


	theta = theta - alpha / m * (X' * (X * theta - y));








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

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

end

end
% 正规方程
function [theta] = normalEqn(X, y)
%NORMALEQN Computes the closed-form solution to linear regression 
%   NORMALEQN(X,y) computes the closed-form solution to linear 
%   regression using the normal equations.

theta = zeros(size(X, 2), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the code to compute the closed form solution
%               to linear regression and put the result in theta.
%

% ---------------------- Sample Solution ----------------------

theta = inv(X' * X) * X' * y;    % 用正规方程求theta


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


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

end
% 在ex1_multi.m 最底部
% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
price = [1, 1650, 3] * theta; % You should change this


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

 

你可能感兴趣的:(机器学习)