吴恩达机器学习III

2022-12-08 14:00:42 浏览数 (1)

吴恩达机器学习III

于2020年11月2日2020年11月2日由Sukuna发布

第一部分:多分类

X:是一个

维的矩阵,里面存的是m组数据集

第一题: 正则化的逻辑回归表达式

代码语言:javascript复制
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=sigmoid(X*theta)
J = (-log(h.')*y - log(ones(1, m) - h.')*(ones(m, 1) - y)) / m  (lambda/(2*m)) * sum(theta(2:end).^2);
grad(1) = (X(:, 1).' * (h - y)) /m;
grad(2:end) = (X(:, 2:end).' * (h - y)) /m   (lambda/m) * theta(2:end);

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

grad = grad(:);

end

第一题就是求正则化的代价函数,这操作基本上一样的,就提一嘴数据集的格式:X是测试用的数据集,每个行向量都是一组数据,h求出来的就是一组0-1向量

第二题: 一对多的分类

代码语言:javascript复制
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);
initial_theta = zeros(size(X, 2), 1);
for c = 1:num_labels
 [all_theta(c, :)] = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options);
end
% ============================================================
end

options = optimset(‘param1′,value1,’param2’,value2,…) %设置所有参数及其值,未设置的为默认值

Parameter

Value

Description

Display

‘off’ | ‘iter’ | ‘final’ | ‘notify’

‘off’ 表示不显示输出; ‘iter’ 显示每次迭代的结果; ‘final’ 只显示最终结果; ‘notify’ 只在函数不收敛的时候显示结果.

MaxFunEvals

positive integer

函数求值运算(Function Evaluation)的最高次数

MaxIter

positive integer

最大迭代次数.

TolFun

positive scalar

函数迭代的终止误差.

TolX

positive scalar

结束迭代的X值.

fmincg这个函数说明的是可以返回

和cost值,具体怎么实现不提,根据这个函数可以求出向量,每次就把行向量的值赋值给X里,迭代即可,返回的是

需要我们

第三题:预测(离散化)迭代函数

这里all_theta是一个

维的矩阵

代码语言:javascript复制
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.
%       
[~, p] = max(X * all_theta.', [], 2);
% ============================================================
end

C = max(A,[],dim)

返回A中有dim指定的维数范围中的最大值。比如C=max(A,[],2),在矩阵中,第2维度表示列,第1维度表示行

max这个函数有两个输出,但是调用这个函数的程序只把第二个输出赋值给了p,不需要第一个输出,于是第一个输出就写成~ 第一个输出就是一个索引表,记录着何时会取最大,这个略过,我们不需要 max:求出最可能的特征的值,求每行最大的值即可 X * all_theta.’乘出来就是一个

维的矩阵,保存的是每一个数据集属于哪一个集合的可能性

第二部分 神经网络

第四题:计算神经网络(不要求反向学习)

代码语言:javascript复制
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.
%
X = [ones(size(X), 1), X]; % Add ones to the X data matrix

X1 = sigmoid(X * Theta1.');

X1 = [ones(size(X1), 1), X1]; % Add ones to the X1 data matrix

[~, p] = max(X1 * Theta2.', [], 2);


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


end

纯计算,theta是已经计算好的矩阵值,就直接算就行,注意要给计算出来的值一个bias值,就是加一个全是1的行

0 人点赞