且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Numpy 计算导数?

更新时间:2021-12-19 05:42:21

您有四个选择

  1. 有限差异
  2. 自动导数
  3. 符号微分
  4. 手动计算导数.

有限差分不需要外部工具,但容易出现数值错误,如果您处于多变量情况,可能需要一段时间.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

如果您的问题足够简单,则符号微分是理想的.如今,符号方法变得非常健壮.SymPy 是一个很好的项目,可以很好地与 NumPy 集成.查看自动换行或lambdify 函数或查看Jensen 关于类似问题的博文.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

自动导数非常酷,不容易出现数字错误,但确实需要一些额外的库(为此谷歌,有一些不错的选择).这是最强大但也是最复杂/最难设置的选择.如果你很好地限制自己使用 numpy 语法,那么 Theano 可能是一个不错的选择.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

这是一个使用 SymPy 的例子

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2⋅x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]