且构网

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

如何使用Numpy计算导数?

更新时间:2022-10-29 09:53:25

您有四个选择

  1. 有限差异
  2. 自动衍生物
  3. 符号区分
  4. 手动计算导数.

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

如果您的问题足够简单,则符号区分是理想的选择.如今,符号方法变得越来越强大. SymPy 是一个出色的项目,可以很好地与NumPy集成.查看autowrap或lambdify函数,或查看 Jensen的博客文章,其中涉及类似问题.

自动导数非常酷,不易出现数字错误,但确实需要一些其他库(为此,google,有一些不错的选择).这是设置选项中最可靠但也最复杂/最困难的.如果您可以限制自己使用numpy语法,那么 Theano 可能是一个不错的选择. >

以下是使用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.]

How do I calculate the derivative of a function, for example

y = x2+1

using numpy?

Let's say, I want the value of derivative at x = 5...

You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

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

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.

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.

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.]