Filter löschen
Filter löschen

dlgradient: covariance matrix derivative.

3 Ansichten (letzte 30 Tage)
MA
MA am 13 Dez. 2021
Beantwortet: MA am 16 Dez. 2021
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.

Akzeptierte Antwort

MA
MA am 16 Dez. 2021
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

Weitere Antworten (1)

yanqi liu
yanqi liu am 14 Dez. 2021
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 Kommentar
MA
MA am 14 Dez. 2021
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Deep Learning Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by