Path: blob/master/Week 4/Programming Assignment - 3/machine-learning-ex3/ex3/oneVsAll.m
864 views
function [all_theta] = oneVsAll(X, y, num_labels, lambda)1%ONEVSALL trains multiple logistic regression classifiers and returns all2%the classifiers in a matrix all_theta, where the i-th row of all_theta3%corresponds to the classifier for label i4% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels5% logistic regression classifiers and returns each of these classifiers6% in a matrix all_theta, where the i-th row of all_theta corresponds7% to the classifier for label i89% Some useful variables10m = size(X, 1);11n = size(X, 2);1213% You need to return the following variables correctly14all_theta = zeros(num_labels, n + 1);1516% Add ones to the X data matrix17X = [ones(m, 1) X];1819% ====================== YOUR CODE HERE ======================20% Instructions: You should complete the following code to train num_labels21% logistic regression classifiers with regularization22% parameter lambda.23%24% Hint: theta(:) will return a column vector.25%26% Hint: You can use y == c to obtain a vector of 1's and 0's that tell you27% whether the ground truth is true/false for this class.28%29% Note: For this assignment, we recommend using fmincg to optimize the cost30% function. It is okay to use a for-loop (for c = 1:num_labels) to31% loop over the different classes.32%33% fmincg works similarly to fminunc, but is more efficient when we34% are dealing with large number of parameters.35%36% Example Code for fmincg:37%38% % Set Initial theta39% initial_theta = zeros(n + 1, 1);40%41% % Set options for fminunc42% options = optimset('GradObj', 'on', 'MaxIter', 50);43%44% % Run fmincg to obtain the optimal theta45% % This function will return theta and the cost46% [theta] = ...47% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...48% initial_theta, options);49%50options = optimset ('GradObj', 'on', 'MaxIter', 50);51initial_theta = zeros(n + 1, 1);52for k = 1:num_labels,53[theta] = fmincg(@(t)(lrCostFunction(t, X, (y == k), lambda)), initial_theta, options);54all_theta(k,:) = theta';55%printf("all_theta(%f, :)",k);56%disp(all_theta(k,:));57end;585960616263646566% =========================================================================676869end707172