Machine Learning (5) -- (ex1 / Week 2 / Coursera)

前面更了四篇理论性的文章,ML这种东西理论讲的再多不亲自动手实践一下是不会融会贯通的,coursera上的练习还是好好自己练习一下,所以如果你正在学这门课,如果发现完成代码练习(即各assignment)有困难,建议一看视频,二看PPT,三看Lecture Notes,四看编程指导文档,试着自己完成作业。如果已经完成或者还是有困难,可以来阅读这一篇帖子,但是个人观点,如果你好好完成了上述四步,应该完成各assignment问题不大。另,切记不要忽略小的bug,ML的各种概念还是略抽象的,任何一个小的bug可能代表你概念理解上的大问题。可能现在还只是线性回归问题不大,随着课程深入到后续内容,就不一定了。养成一个良好的习惯很重要。

言归正传~来说代码,考虑到各种背景,可能会写得比较细。

1. 本练习中涉及的文件:

  • ex1.m – 逐步调试的Octave/MATLAB代码;
  • ex1_multi.m – 后一部分练习的Octave或MATLAB代码;
  • ex1data1.txt – 单一变量线性回归的数据集;
  • ex1data2.txt – 多变量线性回归的数据集;
  • submit.m – 编程作业提交代码,用以将代码提交到Stanford online的服务器;
  • [*] warmUpExercise.m – Octave/MATLAB的热身代码段;
  • [*] plotData.m演示数据集的函数;
  • [*] computeCost.m线性回归的代价计算函数;
  • [*] gradientDesentMultimate.m梯度下降函数;
  • [+] computeCostMulti.m多变量线性回归的代价函数;
  • [+] gradientDescentMulti.m多变量线性回归的梯度下降;
  • [+] featureNormalize.m特征标准化函数;
  • [+] normalEqn.m标准方程计算函数。

[*] 必做;[+] 选做。

1.1 一个简单的Octave/MATLAB函数:ex1.m将用Octave/MATLAB语法向你提供一个练习和作业提交训练。在warmUpExercise.m中,你可以找到关于这个函数的描述。通过写入如下代码将其修改为5×5的单位矩阵。

1.2 完成后运行ex1.m,如果出现如下或类似输出,则证明你的输入是正确的,然后提交:

2. 单一变量的线性回归练习

2.1 这一部分练习将进行用单一变量线性回归预测食品贩卖卡车利润的实现。假设你是一个拥有特权的CEO,你正在考虑在不同的城市开启新的门店。在此之前你已经运行了一些食品贩卖卡车在不同的城市,且你有这些卡车的利润数据和这些城市的人口数据。现在你希望利用这些数据帮助你选择哪个城市派驻新的食品贩卖卡车。

在ex1data1.txt文件中包含了我们线性回归问题所需要的数据集。第一列是各城市的人口,第二列是相应食物贩卖卡车的利润。注意,负值代表亏损。

ex1.m代码已经完成了对这些数据集进行加载的操作了。

2.2 画出数据

2.2.1 一般来说,在开始任何工作之前,通过可视化操作来帮助理解数据总是非常有帮助的。对于这个数据集,你可以用一些列分散的点对数据进行可视化,因为其只有两个需要被标出的特性(利润和人口)。(而许多其他未来在实践中将遇到的问题常常是多维度的,因此很难直接在2-D空间中标记出。)

2.2.2 在ex1.m中,数据集将从数据文件中进行加载,从而得到相应X矩阵和y向量的值:

2.2.3 接下来,ex1代码调用了plotData函数为数据集中的数据创建一系列离散的点。结果应该会是如下的类似情况。

2.3 梯度下降:这个部分将使用梯度下降法逐渐调整线性回归参数θ

2.3.1 迭代方程

  • 梯度下降的目的是最小化代价函数:

  • 其中的假设函数hθ(x)将由如下线性模型得到:

  • 于是整个梯度下降迭代是通过不断调整θ的值,从而寻找到对应代价函数J最小的θ。实现这个目标的方法之一是这里我们将用到的批量梯度下降法,在这个算法中,每一个迭代都会执行如下更新

每一次进行梯度下降,参数θj都会进一步靠近最低的代价函数J(θ)

  • 注意:在矩阵X中,每一个数据案例的内容是用行向量存储的。并且将相应截距项(θ0)也考虑进去,于是在X矩阵的第一列之前再加一列,并将所有值都设定为1,这样做的目的是可以将θ0简单的按照一个额外的特征来对待。另,关于数据集矩阵Xy向量的行列和各项的含义,建议多画几次,加深对各标记和行列含义的理解。此外,关于截距项这个名字出自于二次函数中y=kx+b中的b项,一般来说我们称其为截距。其实个人更喜欢称这个θ0项为偏置项,这样更贴切。

2.3.2 实现:在ex1.m中,我们已经为线性回归设置好了数据。接下来,将θ0项加入其中。并且初始化初始参数为0并将学习率alpha设为0.01:

2.3.3 计算代价函数J(θ)

  • 当用梯度下降法学习最小的代价函数J(θ)时,一件很有帮助的事是通过计算代价值来模拟其收敛趋势。这一部分将设法通过一个函数计算代价函数J(θ)的值。从而检查梯度下降的收敛性。
  • 文件computeCost.m的函数computeCost函数将会计算代价函数J(θ)。(具体内容见代码细节。)

2.3.4 梯度下降

  • 下一步就是在gradientDescent.m文件中实现梯度下降过程。相应的循环结构已经写好了,你的工作就是实现在每一步迭代中对θ的更新。
  • 在进行编程的时候,请一定要明白哪个对象是需要更新的哪个对象是需要优化的。
  • 一个验证梯度下降是否在准确的运行的办法是观察代价值J(θ)的值,并检查其是否随逐次迭代下降。每次迭代,gradientDescent.m的开始部分都将调用computeCost函数,并打印这个代价值。假设你已正确地实现了梯度下降函数computeCost,则你的代码所计算出的J(θ)值应该永远不会随迭代次数而增加,并最终收敛于一个稳定值。

=============================================== 代码部分 ================================================

※ 热身训练 warmUpExercise.m ※

function A = warmUpExercise()
%WARMUPEXERCISE Example function in octave
%   A = WARMUPEXERCISE() is an example function that returns the 5x5 identity matrix

A = [];
% ============= YOUR CODE HERE ==============
% Instructions: Return the 5x5 identity matrix 
%               In octave, we return values by defining which variables
%               represent the return values (at the top of the file)
%               and then set them accordingly. 

A = eye(5);

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


end

※ plotData.m ※

function plotData(x, y)
%PLOTDATA Plots the data points x and y into a new figure 
%   PLOTDATA(x,y) plots the data points and gives the figure axes labels of
%   population and profit.

figure; % open a new figure window

% ====================== YOUR CODE HERE ======================
% Instructions: Plot the training data into a figure using the 
%               "figure" and "plot" commands. Set the axes labels using
%               the "xlabel" and "ylabel" commands. Assume the 
%               population and revenue data have been passed in
%               as the x and y arguments of this function.
%
% Hint: You can use the 'rx' option with plot to have the markers
%       appear as red crosses. Furthermore, you can make the
%       markers larger by using plot(..., 'rx', 'MarkerSize', 10);

plot(x, y, 'rx', 'MarkerSize', 10);  %Plot the data
ylabel('Profit in $10,000s');  % Set the y-axis label
xlabel('Population of City in 10,000s');  % Set the x-axis label

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

end

※ ex1.m ※

%% Machine Learning Online Class - Exercise 1: Linear Regression

%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  linear exercise. You will need to complete the following functions
%  in this exericse:
%
%     warmUpExercise.m
%     plotData.m
%     gradientDescent.m
%     computeCost.m
%     gradientDescentMulti.m
%     computeCostMulti.m
%     featureNormalize.m
%     normalEqn.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%
% x refers to the population size in 10,000s
% y refers to the profit in $10,000s
%

%% Initialization
clear ; close all; clc

%% ==================== Part 1: Basic Function ====================
% Complete warmUpExercise.m
fprintf('Running warmUpExercise ... \n');
fprintf('5x5 Identity Matrix: \n');
warmUpExercise()

fprintf('Program paused. Press enter to continue.\n');
pause;


%% ======================= Part 2: Plotting =======================
fprintf('Plotting Data ...\n')
data = load('ex1data1.txt');
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples

% Plot Data
% Note: You have to complete the code in plotData.m
plotData(X, y);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =================== Part 3: Cost and Gradient descent ===================

X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters

% Some gradient descent settings
iterations = 1500;
alpha = 0.01;

fprintf('\nTesting the cost function ...\n')
% compute and display initial cost
J = computeCost(X, y, theta);
fprintf('With theta = [0 ; 0]\nCost computed = %f\n', J);
fprintf('Expected cost value (approx) 32.07\n');

% further testing of the cost function
J = computeCost(X, y, [-1 ; 2]);
fprintf('\nWith theta = [-1 ; 2]\nCost computed = %f\n', J);
fprintf('Expected cost value (approx) 54.24\n');

fprintf('Program paused. Press enter to continue.\n');
pause;

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

% print theta to screen
fprintf('Theta found by gradient descent:\n');
fprintf('%f\n', theta);
fprintf('Expected theta values (approx)\n');
fprintf(' -3.6303\n  1.1664\n\n');

% 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

% Predict values for population sizes of 35,000 and 70,000
predict1 = [1, 3.5] *theta;
fprintf('For population = 35,000, we predict a profit of %f\n',...
    predict1*10000);
predict2 = [1, 7] * theta;
fprintf('For population = 70,000, we predict a profit of %f\n',...
    predict2*10000);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% ============= Part 4: Visualizing J(theta_0, theta_1) =============
fprintf('Visualizing J(theta_0, theta_1) ...\n')

% Grid over which we will calculate J
theta0_vals = linspace(-10, 10, 100);
theta1_vals = linspace(-1, 4, 100);

% initialize J_vals to a matrix of 0's
J_vals = zeros(length(theta0_vals), length(theta1_vals));

% Fill out J_vals
for i = 1:length(theta0_vals)
    for j = 1:length(theta1_vals)
	  t = [theta0_vals(i); theta1_vals(j)];
	  J_vals(i,j) = computeCost(X, y, t);
    end
end


% Because of the way meshgrids work in the surf command, we need to
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
% Surface plot
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1');

% Contour plot
figure;
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);

※ computeCost.m ※

function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
%   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

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

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

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

end

※ gradientDescent.m ※

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.
    %
    
    
   
    h = X * theta;
    
    theta = theta - (alpha/m) * sum((h - y).*X)';
    
    J = computeCost(X, y, theta);
    






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

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

end

end

=============================================== 代码结束 ================================================

3. 多变量线性回归练习

3.1 在这个部分,练习任务是利用多变量线性回归对房价进行预测。假设你正在销售一个房子,而你期望知道如何能得到一个好的价格。解决这个问题的办法之一是收集最近出售房屋的数据,建立一个关于房价的模型。文件ex1data2.m的内容包含了波特兰的房屋价格训练集数据。第一列是房屋的尺寸(每平方英尺),第二列是卧式的数目,第三列是房屋的价格。

3.2 特征规范化

  • 注意在房价与卧室数量这两个特征上,两者数值之间的差异可以达到1000倍,如果直接处理的话,特征之间的量级差异会造成巨大的问题,由此,特征的规范化就很有必要了。
  • 特征规范化的函数实现在文件featureNormalize.m中,其流程为:
  • 数据集中的每个特征都减去相应的均值;
  • 在减去均值之后,再按照标准差来对各特征值进行缩放。
  • 标准差是一个合理的方法对不同特征在相应特征范围的差异的一个方法,因为一般来说特征值的范围是在均值的±标准差范围内。其可以理解为最大减最小(max - min)的另一种表示方法。在Octave/MATLAB中,你可以使用“std”命令来计算标准差。
  • 例如,在featureNormalize.m文件中,X(:, 1)的量包含了训练集中所有的x1(房屋面积)的值,于是std(X(:, 1))计算了所有房屋面积的标准差。
  • 注意:在实现特征标准化的过程中,将标准化过程中使用过的值存储起来是很有必要的,即相应计算中用到的均值标准差。在完成了模型的学习之后,会需要利用学习好的模型对未出现在数据集中的房屋进行价格预测。在这个时候,需要首先用从前述数据集中得到的均值和标准差对x进行规范化。

3.3 梯度下降

  • 在单一变量中我们已经实现过了梯度下降算法,而对于多变量问题中,唯一的区别是矩阵X中的特征数量变成了多个。
  • 多变量的梯度下降的代价函数和线性回归的实现代码将在文件computeCostMulti.m和gradientDescentMulti.m中。
  • 注意应当支持任意数量的特征,而且其已经被很好的向量化了。

=============================================== 代码部分 ================================================

※ ex1_multi.m ※

%% Machine Learning Online Class
%  Exercise 1: Linear regression with multiple variables
%
%  Instructions
%  ------------
% 
%  This file contains code that helps you get started on the
%  linear regression exercise. 
%
%  You will need to complete the following functions in this 
%  exericse:
%
%     warmUpExercise.m
%     plotData.m
%     gradientDescent.m
%     computeCost.m
%     gradientDescentMulti.m
%     computeCostMulti.m
%     featureNormalize.m
%     normalEqn.m
%
%  For this part of the exercise, you will need to change some
%  parts of the code below for various experiments (e.g., changing
%  learning rates).
%

%% Initialization

%% ================ Part 1: Feature Normalization ================

%% Clear and Close Figures
clear ; close all; clc

fprintf('Loading data ...\n');

%% Load Data
data = load('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);

% Print out some data points
fprintf('First 10 examples from the dataset: \n');
fprintf(' x = [%.0f %.0f], y = %.0f \n', [X(1:10,:) y(1:10,:)]');

fprintf('Program paused. Press enter to continue.\n');
pause;

% Scale features and set them to zero mean
fprintf('Normalizing Features ...\n');

[X mu sigma] = featureNormalize(X);

% Add intercept term to X
X = [ones(m, 1) X];


%% ================ Part 2: Gradient Descent ================

% ====================== YOUR CODE HERE ======================
% Instructions: We have provided you with the following starter
%               code that runs gradient descent with a particular
%               learning rate (alpha). 
%
%               Your task is to first make sure that your functions - 
%               computeCost and gradientDescent already work with 
%               this starter code and support multiple variables.
%
%               After that, try running gradient descent with 
%               different values of alpha and see which one gives
%               you the best result.
%
%               Finally, you should complete the code at the end
%               to predict the price of a 1650 sq-ft, 3 br house.
%
% Hint: By using the 'hold on' command, you can plot multiple
%       graphs on the same figure.
%
% Hint: At prediction, make sure you do the same feature normalization.
%

fprintf('Running gradient descent ...\n');

% Choose some alpha value
alpha = 0.01;
num_iters = 400;

% Init Theta and Run Gradient Descent 
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);

% Plot the convergence graph
figure;
plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');

% Display gradient descent's result
fprintf('Theta computed from gradient descent: \n');
fprintf(' %f \n', theta);
fprintf('\n');

% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
% Recall that the first column of X is all-ones. Thus, it does
% not need to be normalized.
price = 0; % You should change this


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

fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using gradient descent):\n $%f\n'], price);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% ================ Part 3: Normal Equations ================

fprintf('Solving with normal equations...\n');

% ====================== YOUR CODE HERE ======================
% Instructions: The following code computes the closed form 
%               solution for linear regression using the normal
%               equations. You should complete the code in 
%               normalEqn.m
%
%               After doing so, you should complete this code 
%               to predict the price of a 1650 sq-ft, 3 br house.
%

%% Load Data
data = csvread('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);

% Add intercept term to X
X = [ones(m, 1) X];

% Calculate the parameters from the normal equation
theta = normalEqn(X, y);

% Display normal equation's result
fprintf('Theta computed from the normal equations: \n');
fprintf(' %f \n', theta);
fprintf('\n');


% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
price = 0; % You should change this


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

fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using normal equations):\n $%f\n'], price);

※ computeCostMulti.m ※

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 = (1/(2*m)) * (X * theta - y)' * (X * theta - y);

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

end

※ gradientDescentMulti.m ※

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

     h = X * theta;
    
    theta = theta - (alpha/m) * sum((h - y).*X)';
    
    J = computeCost(X, y, theta);
    
    % ============================================================

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

end

end

※ feratureNormalize.m ※

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

[m, n] = size(X);

for i = 1: n
    temp_mu = mean(X(:, i));
    temp_sigma = std(X(:, i));
    mu(i) = temp_mu;
    sigma(i) = temp_sigma;
end

for i = 1:n
    X_norm(:, i) = (X(:, i) - mu(i)) / sigma(i);
end

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

end

※ normalEqn.m ※

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 = pinv(X'*X) * X' * y;

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


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

end

=============================================== 代码结束 ================================================

后续各练习还会在Machine Learning中陆续更新,欢迎讨论共同进步~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值