Andrew Ng's Coursera Machine Leaning Coding Hw 3

机器学习实战:多分类与神经网络预测

Andrew Ng’s Coursera Machine Leaning Coding Hw 3

Author: Yu-Shih Chen
January 3, 2019 6:22AM

Intro:
本人目前是在加州上大学的大二生,对人工智能和数据科学有浓厚的兴趣所以在上学校的课的同时也喜欢上一些网课。主要目的是希望能够通过在这个平台上分享自己的笔记来达到自己更好的学习/复习效果所以notes可能会有点乱,有些我认为我自己不需要再复习的内容我也不会重复。当然,如果你也在上这门网课,然后刚好看到了我的notes,又刚好觉得我的notes可能对你有点用,那我也会很开心哈哈!有任何问题或建议OR单纯的想交流/单纯想做朋友的话可以加我的微信:y802088

Week 4 Coding Assignment

大纲:

  1. Regularized Logistic Regression
  2. One-vs-all classifier training
  3. One-vs-all classifier prediction
  4. Neural Network Prediction Function

Regularized Logistic Regression

这次的作业是检测图片中的数字。我们首先有100个数字的图片,每一个是20x20个pixel的大小。也就是说总共会有400个n(features),因为每一个pixel都是一个因素。总共有5000组数据,也就是5000个数字的图片。

这个section就是要写出我们的cost function J用logistic regression。
code:

function [J, grad] = lrCostFunction(theta, X, y, lambda)
%LRCOSTFUNCTION Compute cost and gradient for logistic regression with 
%regularization
%   J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized logistic regression and the
%   gradient of the cost w.r.t. to the parameters. 

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

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Hint: The computation of the cost function and gradients can be
%       efficiently vectorized. For example, consider the computation
%
%           sigmoid(X * theta)
%
%       Each row of the resulting matrix will contain the value of the
%       prediction for that example. You can make use of this to vectorize
%       the cost function and gradient computations. 
%
% Hint: When computing the gradient of the regularized cost function, 
%       there're many possible vectorized solutions, but one solution
%       looks like:
%           grad = (unregularized gradient for logistic regression)
%           temp = theta; 
%           temp(1) = 0;   % because we don't add anything for j = 0  
%           grad = grad + YOUR_CODE_HERE (using the temp variable)
%

h = X * theta;
J = (1/m) * sum(((-y) .* log(sigmoid(h)) - (1 - y) .* log(1 - sigmoid(h)))) + (lambda/(2*m))*(sum(theta.^2) - theta(1)^2)
grad = 1/m * (X' * (sigmoid(h) - y))
temp = grad(1)
grad = grad + (lambda/m * theta)
grad(1) = temp

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

grad = grad(:);

end

这里还是需要用到sigmoid的function,但是它已经给我们写好了我们就可以直接用。predict function就还是X * theta这个没什么好说的。J就是要写出我们的公式,看起来比较长但其实分开来看的话就还好。第一部分 sum(((-y) .* log(sigmoid(h)) 就是算当y是1的时候,每个y乘以每个log(sigmoig(perdict))。第二部分(1 - y) .* log(1 - sigmoid(h))))就是当y是0的时候。最后一部分(lambda/(2m))(sum(theta.^2) - theta(1)^2)就是他的regularization。

下一部就是计算gradient(因为我们之后需要投入到advanced optimization algorithm里面,所以需要J和gradient。logistic regression的gradient要分为两部分,因为我们第一个元素是个constant,所以就是0。最后出来的grad的矩阵就跟theta是一样的,也就是对应每个theta的。所以先写一个没有reg的grad,然后把第一个grad存到temp里,接着把所有的element加上reg,然后再把第一个grad设回我们之前设的grad。

One-vs-all classifier training

这个section就是要用 advanced optimization algorithm来算出我们要的theta。

function [all_theta] = oneVsAll(X, y, num_labels, lambda)
%ONEVSALL trains multiple logistic regression classifiers and returns all
%the classifiers in a matrix all_theta, where the i-th row of all_theta 
%corresponds to the classifier for label i
%   [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
%   logistic regression classifiers and returns each of these classifiers
%   in a matrix all_theta, where the i-th row of all_theta corresponds 
%   to the classifier for label i

% Some useful variables
m = size(X, 1);
n = size(X, 2);

% You need to return the following variables correctly 
all_theta = zeros(num_labels, n + 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the following code to train num_labels
%               logistic regression classifiers with regularization
%               parameter lambda. 
%
% Hint: theta(:) will return a column vector.
%
% Hint: You can use y == c to obtain a vector of 1's and 0's that tell you
%       whether the ground truth is true/false for this class.
%
% Note: For this assignment, we recommend using fmincg to optimize the cost
%       function. It is okay to use a for-loop (for c = 1:num_labels) to
%       loop over the different classes.
%
%       fmincg works similarly to fminunc, but is more efficient when we
%       are dealing with large number of parameters.
%
% Example Code for fmincg:
%
%     % Set Initial theta
%     initial_theta = zeros(n + 1, 1);
%     
%     % Set options for fminunc
%     options = optimset('GradObj', 'on', 'MaxIter', 50);
% 
%     % Run fmincg to obtain the optimal theta
%     % This function will return theta and the cost 
%     [theta] = ...
%         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
%                 initial_theta, options);
%

for k=1:num_labels
    initial_theta = zeros(n + 1, 1);
    options = optimset('GradObj', 'on', 'MaxIter', 50);
    [theta] = fmincg (@(t)(lrCostFunction(t, X, (y == k), lambda)),initial_theta, options);
    all_theta(k,:) = theta';
end

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

end

这里因为是有multiple class,也就是1,2,3,4…10 有10个class。one-vs-all就是把我们之前学的logistic regression分为10次,每次得出一个不同的theta来计算每一个数字的probability。所以要写一个loop 10次的for loop。最后我们会得到一个10 x n的一个theta的矩阵。

Predict One Vs All

这个section就是用我们上一个section得到的10组theta来计算每一个图片最有可能是哪个数字。

function p = predictOneVsAll(all_theta, X)
%PREDICT Predict the label for a trained one-vs-all classifier. The labels 
%are in the range 1..K, where K = size(all_theta, 1). 
%  p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions
%  for each example in the matrix X. Note that X contains the examples in
%  rows. all_theta is a matrix where the i-th row is a trained logistic
%  regression theta vector for the i-th class. You should set p to a vector
%  of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2
%  for 4 examples) 

m = size(X, 1);
num_labels = size(all_theta, 1);

% You need to return the following variables correctly 
p = zeros(size(X, 1), 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters (one-vs-all).
%               You should set p to a vector of predictions (from 1 to
%               num_labels).
%
% Hint: This code can be done all vectorized using the max function.
%       In particular, the max function can also return the index of the 
%       max element, for more information see 'help max'. If your examples 
%       are in rows, then, you can use max(A, [], 2) to obtain the max 
%       for each row.
%       

[i,j] = max(sigmoid(X * all_theta'),[],2);
p = j;

% =========================================================================
end

这个section其实没有多少code,我们的X是5000x400,我们的all_theta也就是上一个section算出来的theta有10x400,所以sigmoid(X * all_theta’)最后得出来的矩阵是5000x10,因为用了sigmoid所以每一个数字都在0和1之间,都代表每一个class的几率。在这里刚好就是1,2,3,4,5…10 所以每一行的第5个class就是5。所以每一行找出最大的数字的index,预测的值就是那个数字。所以p = j。因为j表示的就是i行的第j个元素。

Neural Network Prediction Function

这个section就是用我们之前写的one-vs-all但是用在neural network里面来表达我们的式子。

function p = predict(Theta1, Theta2, X)
%PREDICT Predict the label of an input given a trained neural network
%   p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the
%   trained weights of a neural network (Theta1, Theta2)

% Useful values
m = size(X, 1);
num_labels = size(Theta2, 1);

% You need to return the following variables correctly 
p = zeros(size(X, 1), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned neural network. You should set p to a 
%               vector containing labels between 1 to num_labels.
%
% Hint: The max function might come in useful. In particular, the max
%       function can also return the index of the max element, for more
%       information see 'help max'. If your examples are in rows, then, you
%       can use max(A, [], 2) to obtain the max for each row.
%

a1 = Theta1 *([ones(m,1) X]');
a2 = [ones(1, m);sigmoid(a1)];
a3 = sigmoid(Theta2 * a2);
 
output =a3';  
[i,j] = max(output, [], 2);  
p = j;

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

end

我们这里有theta1和theta2,至于怎么得到theta1和2的,会在后面的week讲到,这里他直接就给你了只是让你有个idea。这里我们的neural network总共有3层,然后第三层就是我们的结果。他就是一层一层的带入公式,最后会得到一个矩阵,然后就还是跟之前一样,最大的概率的index就是我们的‘答案’。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值