背景
当目标函数非线性时(比如下图明显需要一条曲线),就需要增加高次项来获得曲线,当特征数量比较多时,增加高次项会使特征数量爆炸式增长。 比如图像识别问题,对50 * 50像素的图像,如果将每个像素作为特征,增加二次特征就会产生约3 * 10 ^ 6个特征(C22500 = 2500 * 2499 / 2) 这种情况下,若要使用普通逻辑回归学习所有特征,计算量就过大了。
此时用神经网络学习这种复杂的非线性假设函数,就比较合适了。
神经网络
首先学习几个术语: dendrite: 树突(输入) cell body: 细胞体 nucleus:细胞核 node of ranvier:郎飞氏结 schwann cell:施万细胞 myelin sheath:髓鞘 axon:轴突(输出) axon terminal:轴突终末
神经网络架构
类似神经元,神经网络的架构如下。重要组成元素有: input layer:输入层,即第一层; hidden layer:隐藏层,即中间层; activation units:激活单元,即隐藏层中的节点; output layer:输出层,即最后一层,得到最终结果;
注意a0总是为1,只出现在上一层的输入,不出现在下一层的输出。例如,用x0-x4计算出a1-a3:
a的计算如下:
向量化计算
a的计算就可表示为: a(j) = g(z(j)) = g(θ(j-1) * a(j-1))
若a(j)是sj维向量,那么就要求θ(j-1) 是sj * (sj-1 + 1)的矩阵。
中间层的特征是靠自学的
输入层使用的特征是X的原始特征,隐藏层使用的特征是上一层训练出来的新的特征。
如果只看最后两层,其实和逻辑回归一样。
简单例子
and
or
not
组合出 xnor
多分类问题
相当于one-vs-all方法的扩展,需要几个分类,分别对应几个输出节点即可:
作业
测试题:Neural Networks: Representation
第1题容易做错:
第1个选项:单层感知机无法解决线性不可分问题,XOR就是线性不可分的 第4个选项:神经网络的输出并非概率,输出结果的和不一定为1。
第5题,同时交换θ(1) 和θ(2) 后,交换效果相当于抵消了。
大作业:Multi-class Classification and Neural Networks
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 = (-log(hx)' * y - log(1-hx)' * (1 - y)) / m + lambda * (theta(2:end)' * theta(2:end)) / 2 / m;
grad0 = X(:,1)' * (hx - y) / m;
grad1 = X(:,2:end)' * (hx - y) / m + lambda * theta(2:end) / m;
% =============================================================
grad = [grad0;grad1];
end
oneVsAll.m
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
% 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);
%
% 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
for c = 1:num_labels,
[theta] = ...
fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
initial_theta, options);
all_theta(c,:) = theta';
end
% =========================================================================
end
predictOnesVsAll.m
通过one-vs-all方法的结果来预测:
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(sigmoid(X * all_theta'), [], 2);
% =========================================================================
end
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.
%
X = [ones(m, 1) X];
a2 = sigmoid(X * Theta1');
a2 = [ones(m, 1) a2];
a3 = sigmoid(a2 * Theta2');
[~, p] = max(a3, [], 2);
% =========================================================================
end
|