【问题标题】:Calculate the derivative of the sum of a mathematical function-MATLAB计算一个数学函数之和的导数-MATLAB
【发布时间】:2014-11-02 10:12:19
【问题描述】:

在 Matlab 中,我想创建一个名为 J(theta_0, theta_1) 的成本函数的偏导数(以便进行梯度下降所需的计算)。

函数J(theta_0, theta_1)定义为:

让我们说h_theta(x) = theta_1 + theta_2*x。另外:alpha 是固定的,theta_1theta_2 的起始值是给定的。假设在这个例子中:alpha = 0.1theta_1 = 0theta_2 = 1我还拥有两个不同向量中的 x 和 y 的所有值

VectorOfX = 
5
5
6

VectorOfX = 
6
6
10

我在 Matlab 中尝试解决这个问题的步骤:我不知道如何在 matlab 中解决这个问题。所以我开始尝试在 Matlab 中定义一个函数并尝试了这个:

theta_1 = 0
theta_2 = 1
syms x;
h_theta(x) = theta_1 + t2*x;

这行得通,但不是我真正想要的。我想得到 x^(i),它在一个向量中。接下来我尝试的是:

theta_1 = 0
theta_2 = 1
syms x;
h_theta(x) = theta_1 + t2*vectorOfX(1);

这会产生以下错误:

Error using sym/subsindex (line 672)
Invalid indexing or function definition. When defining a
function, ensure that the body of the function is a SYM
object. When indexing, the input must be numeric, logical or
':'.

Error in prog1>gradientDescent (line 46)
h_theta(x) = theta_1 + theta_2*vectorOfX(x);

我查找了此错误,但不知道如何解决此特定示例。我觉得我让 matlab 对我不利,而不是对我有利。

【问题讨论】:

  • 自己区分函数不是更容易吗?你为什么坚持 MATLAB 做呢?
  • 这可能会更容易一些,尽管我上面描述的问题仍然存在。即使有差异,我仍然必须对范围 h_theta(x^(i)) 和 y^(i) 求和。
  • 这是家庭作业吗?如果是这样,明智的做法是在您的问题中指定它。

标签: matlab function derivative


【解决方案1】:

当我必须执行符号计算时,我更喜欢使用 Mathematica。在那种环境中,这是获取您正在寻找的偏导数的代码。

J[th1_, th2_, m_] := Sum[(th1 + th2*Subscript[x, i] - Subscript[y, i])^2, {i, 1, m}]/(2*m)
D[J[th1, th2, m], th1]
D[J[th1, th2, m], th2]

并给予

回到 MATLAB 我们可以用下面的代码解决这个问题

%// Constants.
alpha = 0.1;
theta_1 = 0;
theta_2 = 1;
X = [5 ; 5 ; 6];
Y = [6 ; 6 ; 10];

%// Number of points.
m = length(X);

%// Partial derivatives.
Dtheta1 = @(theta_1, theta_2) sum(2*(theta_1+theta_2*X-Y))/2/m;
Dtheta2 = @(theta_1, theta_2) sum(2*X.*(theta_1+theta_2*X-Y))/2/m;

%// Loop initialization.
toll = 1e-5;
maxIter = 100;
it = 0;
err = 1;
theta_1_Last = theta_1;
theta_2_Last = theta_2;

%// Iterations.
while err>toll && it<maxIter
    theta_1 = theta_1 - alpha*Dtheta1(theta_1, theta_2);
    theta_2 = theta_2 - alpha*Dtheta2(theta_1, theta_2);

    it = it + 1;
    err = norm([theta_1-theta_1_Last ; theta_2-theta_2_Last]);
    theta_1_Last = theta_1;
    theta_2_Last = theta_2;
end

不幸的是,在这种情况下,迭代不会收敛。

MATLAB 对于符号计算不是很灵活,但是获得这些偏导数的方法如下

m = 10;
syms th1 th2
x = sym('x', [m 1]);
y = sym('y', [m 1]);
J = @(th1, th2) sum((th1+th2.*x-y).^2)/2/m;
diff(J, th1)
diff(J, th2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多