How to use dlgradient for computing second derivative?

The following code gives me an error.
x0 = dlarray([-1,2]);
[fval,gradval] = dlfeval(@rosenbrock,x0)
function [y,dy2dx] = rosenbrock(x)
y = 100*(x(2) - x(1).^2).^2 + (1 - x(1)).^2;
dydx = dlgradient(y,x);
dy2dx= dlgradient(dydx,x);
end
I am using dlgradient to compute the second derivative but getting the following error:
"Error using dlfeval (line 43)
Value to differentiate must be a traced dlarray scalar."
Any help on what am i doing wrong? Thanks.

 採用された回答

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 9 月 10 日

0 投票

Hi, You are using dlgradient wrong, first agument of dlgradient should be scalar. after 1 gradient from y respect to x. gradient return 1by2 vector. they are and . so you cannot use dydx again in dlgradient. also for second derivative you have 4 elements : , , ,
also you should specify option EnableHigherDerivatives in dlgradient.
so substiture your function with this :
function [y,dy2dx] = rosenbrock(x)
y = 100*(x(2) - x(1).^2).^2 + (1 - x(1)).^2;
dydx = dlgradient(y,x,'EnableHigherDerivatives',true);
dy2dx(1,1:2)= dlgradient(dydx(1),x);
dy2dx(2,1:2)= dlgradient(dydx(2),x);
end

5 件のコメント

Rahul Gulati
Rahul Gulati 2021 年 9 月 10 日
Thanks a lot Abolfazl!
Also, would you know which version of Matlab should i be using for this?
R2020b gives me an error that 'EnableHigherDerivatives' is unrecognised but this works totally fine in the Matlab online version.
Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 9 月 10 日
Yes, your are right. the option 'EnableHigherDerivatives' added in 2021a. i test on 2020b. it won't work.
it's seems all example with higher derivative dlgradient just added in 2021a, e.g. WGAN and PDE.
  • https://www.mathworks.com/help/deeplearning/ug/trainwasserstein-gan-with-gradient-penalty-wgan-gp.html
  • https://www.mathworks.com/help/deeplearning/ug/solve-partial-differential-equations-using-deep-learning.html
Rahul Gulati
Rahul Gulati 2021 年 9 月 10 日
This is very helpful. Thanks a lot again, Abolfazl!
Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 9 月 10 日
Glad to help .
Sanaz Zanjani Foumani
Sanaz Zanjani Foumani 2021 年 12 月 29 日
Do you know how I can use dlgradiet in fmincon? I mean I want to use automatic derevative in fmincon insted of analytical derevative.

サインインしてコメントする。

その他の回答 (0 件)

製品

リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by