dlgradient: covariance matrix derivative.

3 次查看(过去 30 天)
Assuming I have a matrix x of size (mxn), the covariance matrix is of the size nxn. I want to find the gradient of the covariance matrix with respect to the input. So, starting with this code:
function [y,dx]=cov_der(x)
y=x'*x;
dx=dlgradient(y,x,'EnableHigherDerivatives',true);
end
and evaluating it as:
[y,dx]=dlfeval(@cov_der,x)
This does not work for matrices but it works for scalars. So, is there anyway I could find the gradient with respect to every element in the matrix. THanks.

采纳的回答

MA
MA 2021-12-16
I actually solve it. For anyone looking for the same problem:
function [y,dx]=cov_der(x)
%simple example
%x=dlarray(and(3,3));
%[y,dx]=dlfeval(@cov_der,x)
y=zeros(size(x,2),size(x,2));
z=size(x,1);
y=dlarray(y);
for i=1:size(x,2)
for j=1:size(x,2)
y(i,j)=sum(x(:,i).*x(:,j))./z;
end
end
dx=zeros(size(x,2)*size(x,2),size(x,1),size(x,2));
index=1;
for i=1:size(x,2)
for j=1:size(x,2)
dx(index,:,:)=dlgradient(y(i,j),x,'EnableHigherDerivatives',true);
index=index+1;
end
end
end

更多回答(1 个)

yanqi liu
yanqi liu 2021-12-14
yes,sir,may be use loop for every element in matrix
clc; clear all; close all;
[X1, X2] = meshgrid(linspace(0,1,10));
X1 = dlarray(X1(:));
for i = 1:length(X1)
[y(i),dx(i)]=dlfeval(@cov_der, dlarray(X1(i)));
end
% figure; plot(extractdata(X1),extractdata(y))
% hold on;
% plot(extractdata(X1),extractdata(dx))
function [y,dx]=cov_der(x)
y=x'*x;
dx=dlgradient(y,x,'EnableHigherDerivatives',true);
end
  1 个评论
MA
MA 2021-12-14
THanks for your answer, but in this example you gave the covariance is calculated for each point. I want to calculate the covariance matrix for a matrix of size mxn so the output (y) will be of size nxn.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Deep Learning Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by