【发布时间】:2017-07-23 14:08:41
【问题描述】:
我在 coursera 上参加 Andrew Ng 的机器学习课程,我很困惑为什么一个特定的例子适用于 One vs. All 分类:
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
% logisitc 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 use
% 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);
%
initial_theta = zeros(n + 1, 1);
options = optimset('GradObj', 'on', 'MaxIter', 50);
for i = 1:num_labels
c = i * ones(size(y));
fprintf('valores')
[theta] = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options);
all_theta(i,:) = theta;
end
% =========================================================================
end
我对这条线特别困惑:[theta] = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options);。 lrCostFunction被定义为有参数theta, X, y, lambda,所以我不知道t在那里做什么。
另外,将theta 括在括号中的目的是什么:[theta]?
任何有关单步执行此代码的帮助都会很棒。谢谢。
【问题讨论】:
-
Andrew Ng 在他的作业以及他的 Octave / MATLAB 教程中深入介绍了这一点。还要检查副本。另外,用
[]包围的theta是多余的。通常,您有一个可以返回多个输出的函数,因此您通常通过在逗号分隔的列表中将[]包围来捕获您想要捕获的每个变量。在这种情况下,函数只返回一个变量,因此 MATLAB 中的语法糖允许我们在一个变量的情况下删除[]。否则,用[]包围输出变量并省略它们都没有区别。
标签: matlab machine-learning function-handle