Cara menggunakan derivatives in python

In machine learning, derivatives are used for solving optimization problems. Optimization algorithms such as gradient descent use derivatives to decide whether to increase or decrease the weights in order to get closer and closer to the maximum or minimum of a function. This post covers how these functions are used in Python.

Symbolic differentiation manipulates a given equation, using various rules, to produce the derivative of that equation. If you know the equation that you want to take the derivative of, you can do symbolic differentiation in Python. Let’s use this equation as an example:

f(x) = 2x2+5

Import SymPy

In order to do symbolic differentiation, we’ll need a library called SymPy. SymPy is a Python library for symbolic mathematics. It aims to be a full-featured computer algebra system (CAS). First, import SymPy:

from sympy import *

Make a symbol

Variables are not defined automatically in SymPy. They need to be defined explicitly using

x = symbols('x')
3.
x = symbols('x')
3 takes a string of variable names separated by spaces or commas, and creates Symbols out of them. Symbol is basically just the SymPy term for a variable.

Our example function f(x) = 2x2+5 has one variable x, so let’s create a variable for it:

x = symbols('x')

If the equation you’re working with has multiple variables, you can define them all in one line:

x, y, z = symbols('x y z')

Symbols can be used to create symbolic expressions in Python code.

>>> x**2 + y         
x2+y
>>> x**2 + sin(y)   
x2+sin(y)

Write symbolic expression

So, using our Symbol x that we just defined, let’s create a symbolic expression in Python for our example function f(x) = 2x2+5:

f = 2*x**2+5

Take the derivative

Now, we’ll finally take the derivative of the function. To compute derivates, use the

x = symbols('x')
5 function. The first parameter of the diff function should be the function you want to take the derivative of. The second parameter should be the variable you are taking the derivative with respect to.

x = symbols('x')
f = 2*x**2+5

df = diff(f, x)

The output for the

x = symbols('x')
6 and
x = symbols('x')
7 should look like this:

>>> f
2*x**2+5
>>> df
4*x

You can take the nth derivative by adding an optional third argument, the number of times you want to differentiate. For example, taking the 3rd derivative:

d3fd3x = diff(f, x, 3)

Substituting values into expressions

So we are able to make symbolic functions and compute their derivatives, but how do we use these functions? We need to be able to plug a value into these equations and get a solution.

We can substitute values into symbolic equations using the

x = symbols('x')
8 method. The
x = symbols('x')
8 method replaces all instances of a variable with a given value.
x = symbols('x')
8 returns a new expression; it doesn’t modify the original one. Here we substitute 4 for the variable
x, y, z = symbols('x y z')
1 in
x = symbols('x')
7:

>>> df.subs(x, 4)
16

To evaluate a numerical expression into a floating point number, use 

x, y, z = symbols('x y z')
3.

>>> df.subs(x, 4).evalf()
16.0

To perform multiple substitutions at once, pass a list of

x, y, z = symbols('x y z')
4 pairs to 
x = symbols('x')
8. Here’s an example:

x = symbols('x')
0

The lambdify function

If you are only evaluating an expression at one or two points,

x = symbols('x')
8 and
x, y, z = symbols('x y z')
3 work well. But if you intend to evaluate an expression at many points, you should convert your SymPy expression to a numerical expression, which gives you more options for evaluating expressions, including using other libraries like NumPy and SciPy.

The easiest way to convert a symbolic expression into a numerical expression is to use the

x, y, z = symbols('x y z')
8 function.

The

x, y, z = symbols('x y z')
8 function takes in a Symbol and the function you are converting. It returns the converted function. Once the function is converted to numeric, you can Let’s convert the function and derivative function from our example.

There are so many cool things you can do in Python, and today we're going to learn about calculating derivatives.

What's a Derivative

Remember Calculus 1? Me neither, so let's do a quick refresher.

Derivatives are how you calculate a function's rate of change at a given point. For example, acceleration is the derivative of speed. If you have a function that can be expressed as f(x) = 2x^2 + 3 then the derivative of that function, or the rate at which that function is changing, can be calculated with f'(x) = 4x.

Note: In case you don't know, the f'(x) is pronounced "f prime of x"

Derivatives have a lot of use in tons of fields, but if you're trying to figure out how to calculate one with Python, you probably don't need much more explanation from me, so lets just dive in.

Fire up that Python Console

If you don't already have the SymPy library, go ahead and run pip install sympy. SymPy is a Python library aiming to become a full fledged Computer Algebra System (CAS) which is a really freaking cool thing in its own right, but lets press on. First, let's get everything set up:

>>> from sympy import *
>>> # We have to create a "symbol" called x
>>> x = Symbol('x')

Enter fullscreen mode Exit fullscreen mode

Now that we've imported the library and created a symbol, let's make the function for 2x^2 + 3 (the math function, not a Python function):

>>> f = 2*x**2+3
>>> f_prime = f.diff(x)

Enter fullscreen mode Exit fullscreen mode

And what do these look like?

>>> f
2*x**2+3
>>> f_prime
4*x

Enter fullscreen mode Exit fullscreen mode

And that's all there really is to it. But those aren't actual functions, so what good are they to me unless I'm just trying to cheat on my homework? If I were writing a program that went through the trouble of finding a derivative, I'm probably intending to use it as a function, right? Well, SymPy has your back with a handy function called lambdify in which we pass our symbol and (math) function:

>>> f = lambdify(x, f)
>>> f_prime = lambdify(x, f_prime)
>>> # Let's test it out
>>> f(3)
21
>>> f_prime(3)
12

Enter fullscreen mode Exit fullscreen mode

And there you have it. So easy, right??

Conclusion

If you made it this far into the article and you're thinking to yourself "I will literally never use this" consider this: If there is a Python library for finding derivatives and then turning them into functions, there is probably a library for anything you might need. If you ever find yourself about to take on a really complex task, or you have a great idea for an application but are afraid the underlying implementation will be too much to write on your own, do a quick Google search and see if there isn't something out there already.