Coursera-Machine-Learning-ex3

这一部分练习,我们使用逻辑回归和神经网络识别手写数字。

Multi-class Classification

首先载入5000个训练样本的矩阵,每一个训练样本是20x20像素的灰度值,并且被展开成一个400维向量,成为矩阵中的一行。而第二部分就是这5000个样本的标签,为一个5000维向量,分别对应其正确值。

我们首先随机选择其中的100行,使用displayData方法展示出这100个样本。

接着我们利用one-vs-all逻辑回归模型来建立多目标分类器,由于共有十个数字,我们需要训练十个分类器,因此利用向量化可以使我们的训练过程更加有效率。首先在代价函数方面,由于不进行正则化的情况下,代价函数为:

其中h(x)为sigmoid function,所以我们利用矩阵乘法进行计算,首先定义:

那么可以得到:

同理对于梯度部分,原本的各个偏导公式为:

我们可以将所有的偏导写成一个向量:

其中h(x)和y均为m维向量,而通过以下公式可以得到最后一步的等式:

这样我们就避免了使用循环来计算所有的偏导项,之后我们加入正则化项,分别更改代价函数和偏导项,修改后的lrCostFunction.m代码如下:

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

hx = sigmoid(X*theta);
J = -(y'*log(hx)+(1-y)'*log(1-hx))/m+lambda/(2*m)*sum(theta(2:end,:).^2);
theta(1) = 0;
grad = 1/m*X'*(hx-y)+lambda/m*theta;

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

grad = grad(:);

end

接下来需要完成onVsAll.m的代码,其中内容为使用fimcg方法训练出适合的θ,最后得到十个匹配的θ值:

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);
%
% =========================================================================

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

得到了十个对应的θ值后我们利用其进行手写数字的预测,即分别计算是十个数字的概率,predictOneVsAll.m代码如下:

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

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

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


end

Neural Networks

神经网络部分,我们重新使用一个算法来进行计算。对于神经网络,我们的输入层有400+1个输入单元,我们已经有了一组训练好的权重矩阵,分别用于第二层25个神经元和最终10个输出单元。接下来我们需要完成向后传播的代码,并且返回神经网络的预测结果。

首先为X增加偏差单元,成为一个100*401阶矩阵,通过权重矩阵25*401阶,得到一个25*100阶矩阵,然后依次计算,最后每个样本都得到一个10维向量,取其中最大值下标为预测值,predict.m代码如下:

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=[ones(m,1) X];
size(Theta1)
z2=Theta1*a1';
a2=[ones(1,m);sigmoid(z2)];
z3=Theta2*a2;
output=z3';
[c,i]=max(output,[],2);
p=i;

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


end

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值