吴恩达机器学习正则化Logistic算法与神经网络的MATLAB实现(对应ex3练习)
lrCostFunction.m文件
这部分其实完全是logistic算法的正则化实现,根据作业的要求,不能使用循环实现,目的是使用向量的方式来计算J和梯度。下面附上原理公式。
这里值得注意的有两点:1、在计算J(θ)时,注意后面的累加项的j是从1开始的,也就是说并没有累加第一项0。这点在吴恩达的授课视频中也专门指出来过。在用MATLAB实现时,由于其中序号是从1开始的 ,所以在累加时应该从2开始;2、在计算j≥1时的梯度时,同样的不能把第0项(MATLAB中是第1项)加进来。下面附实现代码,其中的theta(2:end,:)意思就是抛弃第1项。
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)
%
% theta 4*1;X 5*4;y 5*1;lambda 3
h = sigmoid(X*theta);%5*1
J = sum(-y' * log(h) - (1 - y)' * log(1 - h)) / m + lambda / (2 * m) * sum(theta(2:end,:) .* theta(2:end,:));
grad(1,:) = 1 / m * sum((h - y) .* X(:,1));
grad(2:end,:) = X(:,2:end)' * (h - y) ./ m + lambda / m .* theta(2:end,:);
% =============================================================
% grad = grad(:);
end
oneVsAll.m文件
这个文件本身实现起来并没有什么难度,注释里面已经写的很清楚了,就差贴出源码了。关键是理解这样做的目的。首先贴出源码。
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);%10 * 401
% Add ones to the X data matrix
X = [ones(m, 1) X];%5000 * 401
% ====================== 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);
%
% X 5000 * 400;Y 5000 * 1;num_labels 10;lambda 0.1
for c = 1 : num_labels,%需要循环10次的原因是需要划分10个类别。类比于logistic划分两个类别只需要1次。
init_theta = zeros(n + 1,1);
options = optimset('GradObj','on','MaxIter',50);
init_theta = fmincg(@(t)lrCostFunction(t,X,(y == c),lambda),init_theta,options);
all_theta(c,:) = init_theta';
end
% =========================================================================
end
这里最关键是使用循环实现fmincg函数,该函数与之前学习的fminunc函数的使用极其相似,其中构造options的方法和调用都基本一样。因为在本次的例子中需要划分10个数字,所以循环了十次。类比ex2中区分两种情况只需要一次调用。
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);%5000
num_labels = size(all_theta, 1);%10
% You need to return the following variables correctly
p = zeros(size(X, 1), 1);%5000*1
% Add ones to the X data matrix
X = [ones(m, 1) X];%5000 * 401
% ====================== 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.
%
h=sigmoid( X*all_theta');%5000 * 10 每个输入对应1-10之间的概率 选取其中概率最大的作为预测结果
[h_max,col_num]=max(h,[],2); %求出每行最大的值
p = col_num';
%%%以下是网上的另一种方法,思想也是找每个输入对应的最大概率,完全可以利用函数max(上面的)实现
% for i=1:size(X,1),
% for j=1:num_labels,
% if h_max(i)==h(i,j),
% p(i)=j;
% break;
% end
% end
% end
% =========================================================================
end
predict.m文件
这部分文件是使用神经网络来做预测,对于一个输入经过三层神经网络:输入层、隐藏层、输出层后输出结果。关键点是理解每层的计算方法,这里贴出具体实现步骤如下。
需要注意的是每层记得添加偏置层,其值为1。对于隐藏层,正如上图所示,a2=g(z2),其中z2 =θ1x,x为添加偏置层后的输入,便于理解也可以看成a1,。同理a3=g(z2),z2= θ2a2。代码体现如下。
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];%添加偏置单元 这里其实是把输入层看成了a1 类比于PPT上更利于理解
for i = 1 : m,
a2 = sigmoid(Theta1 * a1(i,:)');
a2 = [1;a2];
a3 = sigmoid(Theta2 * a2);
[maxVal colNum] = max(a3);
p(i) = colNum;
end
% =========================================================================
end