本文介绍了符号向量函数的Matlab梯度和hessian计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Matlab的梯度"和"hessian"函数来计算符号向量函数相对于向量的导数.下面是使用S型函数1/(1 + e ^(-a))的示例,其中a是特征向量乘以权重.以下所有版本均返回错误.我是Matlab的新手,非常感谢您提供任何建议.在文档中,解决方案很可能在我的脑海中.无法解决问题.预先感谢您的帮助!

I am trying to use the Matlab "gradient" and "hessian" functions to calculate the derivative of a symbolic vector function with respect to a vector. Below is an example using the sigmoid function 1/(1+e^(-a)) where a is a feature vector multiplied by weights. The versions below all return an error. I am new to Matlab and would very much appreciate any advice. The solution may well be under my nose in the documentation, but I have not been able to solve the issue. Thank you in advance for your help!

%version 1
syms y w x
x = sym('x', [1 3]);
w = sym('w', [1 3]);
f = (y-1)*w.*x + log(1/(1+exp(-w.*x)));
gradient(f, w)

%version 2
syms y w1 w2 w3 x1 x2 x3 x w
x = [x1,x2,x3];
w = [w1,w2,w3];
f = (y-1)*w.*x + log(1/(1+exp(-w.*x)));

%version 3
syms y w1 w2 w3 x1 x2 x3
f = (y-1)*[w1,w2,w3].*[x1,x2,x3] + log(1/(1+exp(-[w1,w2,w3].*[x1,x2,x3])));

推荐答案

谢谢Daniel,事实证明,问题出在没有使用dot()来获取w和x的点积. diff()和gradient()给出了相同的解决方案,如下所示:

Thanks, Daniel - it turns out the problem was in not having used dot() to take the dot product of w and x. Both diff() and gradient() gave the same solution, shown below:

syms y
x = sym('x', [1 3]);
w = sym('w', [1 3]);
f = (y-1)*dot(w,x) + log(1/(1+exp(dot(-w,x))));
diff(f, w(1))
gradient(f, w(1))

%ans =
%x1*(y - 1) + (x1*exp(- x1*conj(w1) - x2*conj(w2) - x3*conj(w3)))/
    (exp(-x1*conj(w1) - x2*conj(w2) - x3*conj(w3)) + 1)

这篇关于符号向量函数的Matlab梯度和hessian计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:22