矩阵微分
定义
对于一个函数
f:Rm×n−→R
,从
m×n
的矩阵映射到一个实数,那么
f
关于
∇Af(A)=⎡⎣⎢⎢⎢⎢⎢⎢⎢∂f∂A11⋮∂f∂Am1⋯⋱⋯∂f∂A13⋮∂f∂Amn⎤⎦⎥⎥⎥⎥⎥⎥⎥
所以梯度 ∇Af(A) 本身也是一个 m×n 的矩阵。
例如,
A=[A11A21A12A22]
为一个 2×2 的矩阵,函数 f:R2×2−→R 为
f(A)=32A11+5A212+A21A22
那么,记 Aij 为 A 的第
∇Af(A)=⎡⎣32A2210A12A21⎤⎦
矩阵的迹
对一个
n×n
的方阵,
A
的迹为其对角线上的元素之和:
性质
- 如果
a
为一个实数,则
tra=a 。 - 如果矩阵
A
和
B 的乘积为方阵,则 trAB=trBA 。这可以推广到更一般的情况:
trABC=trCAB=trBCA
trABCD=trDABC=trCDAB=trBCDA - 如果矩阵
A
和
B 同为方阵, a 为实数,则:
trA=trAT
tr(A+B)=trA+trB
traA=atrA - 通过简单推导出可以得到矩阵的迹的梯度:
∇AtrAB=BT
∇Af(A)=(∇Af(A))T
∇AtrABATC=CAB+CTABT
∇A|A|=|A|(A−1)T
上面最后一式中, A 为非奇异方阵,|A| 为 A 的行列式的值。
例子
假设
那么损失函数可以记为:
J(θ)=12(θX−y)(θX−y)T
现在求解损失函数的梯度,
∇θJ(θ)=∇θ[12(θX−y)(θX−y)T]=12∇θ(θXXTθ−θXyT−yXTθT+yyT)=12∇θ(θXXTθ−θXyT)−∇θ(θXyT)=12(θXXT+θXXT)−yXT=θXXT−yXT
可得, θ=yXT(XXT)−1 。
linearRegressionTrain.m
function [linearRegressionModel] = linearRegressionTrain(inputData, labels, options)
% linearRegressionTrain Train a linear Regression model on the given
% data. Returns softmaxOptTheta, a vector containing the trained parameters
% for the model.
%
% inputData: an N by M matrix containing the input data, such that
% inputData(:, c) is the cth input
% labels: M by 1 matrix containing the value labels for the
% corresponding inputs. labels(c) is the value label for
% the cth input
% options (optional): options
% options.maxIter: number of iterations to train for
if ~exist('options', 'var')
options = struct;
end
if ~isfield(options, 'pinv')
options.pinv = true;
end
[row, col] = size(inputData);
inputData = [ones(1, col); inputData];
if options.pinv
theta = (labels * inputData') * pinv(inputData * inputData');
else
theta = (labels * inputData') * inv(inputData * inputData');
end
% Fold softmaxOptTheta into a nicer format
linearRegressionModel.optTheta = theta;
linearRegressionModel.numSample = col;
linearRegressionModel.numDim = row;
end
linearRegressionPredict.m
function [pred] = linearRegressionPredict(linearRegressionModel, data)
% linearRegressionModel - model trained using linearRegressionTrain
% data - the N x M input matrix, where each column data(:, i) corresponds to
% a single test set
%
% This code produces the prediction matrix
% pred, where pred(i) is the ith pred.
theta = linearRegressionModel.optTheta; % the parameters from theta
pred = theta * [ones(1, size(data, 2)); data];
% pred= max(peed_temp);
% ---------------------------------------------------------------------
end