Derivative python что это

Производные в Python с использованием симпы

Как рассчитать производные в Python? В этой статье мы будем использовать Sympy Sympy Python, чтобы играть с производными.

Производные в Python с использованием симпы

Как рассчитать производные в Python? В этой статье мы будем использовать Sympy Sympy Python, чтобы играть с производными.

Какие производные?

Производные являются фундаментальными инструментами исчисления. Это очень полезно для оптимизации функции потери с Градиентный спуск в Машинное обучение возможно только из-за производных.

Предположим, у нас есть функция y = F ( X ), который зависит от х Затем вывод этой функции означает скорость, при которой значение y функции изменяется с изменением х Отказ

Это ни отнюдь означает статью о основах производных, она не может быть. Исчисление – это другой зверь, который требует особого внимания. Я предполагаю, что у вас есть какой-то опыт в исчислении. Эта статья предназначена для продемонстрирования того, как мы можем дифференцировать функцию с использованием симпы-библиотеки.

Решение производных в Python с использованием Sympy

Sympy – библиотека Python для символической математики.

Он стремится стать полнофункциональной системой компьютерной алгебры (CAS), сохраняя максимально простую код, остынет, не так ли.

1. Установите Sympy, используя PIP

Sympy имеет больше используемых, чем просто расчет производных, но на данный момент мы сосредоточимся на производных.

Беги PIP Установить Sympy Для установки с помощью Диспетчер пакетов PIP Отказ

2. Решение дифференциала с Sympy Diff ()

Для дифференциации Sympy предоставляет нам Различать способ вывода производной функции.

Посмотрим, как мы можем достичь этого, используя Sympy.

Объявление символа похоже на то, что наша функция имеет переменную «X» или просто функция зависит от x.

3. Решение производных в Python

Теперь для расчета производной функции на Sympy есть лямбдифицировать Функция, в которой мы передаем символ и функцию.

Основные производные правила в Python Sympy

Есть определенные правила, которые мы можем использовать для расчета производной дифференцируемых функций.

Некоторые из наиболее встречающихся правил:

Давайте погрузимся в то, как мы можем использовать Simpy для расчета производных, подразумеваемых правилами общей дифференцировки.

1. Правило питания

Пример, функция у нас есть:

Это производное будет: (5-1) 4.

2. Правило продукта

Пусть u (x) и v (x) будут дифференцируемыми функциями. Тогда продукт функций u (x) v (x) также дифференцируемый.

3. Правило цепочки

Правило цепочки рассчитывает производное состав функций.

Этот процесс может быть расширен для коэффициента правила также. К настоящему времени необходимо очевидно, что только функция меняется, в то время как процесс приложения остается прежним, остальное заботится о самой библиотеке.

Производные многомерные функции с использованием Sympy

Примеры, которые мы видели выше, имели одну переменную. Но мы более склонны столкнуться с функциями, имеющими более одной переменной в них. Такие производные, как правило, называются частичными производными.

Частичное производное многомерной функции представляет собой производное относительно одной переменной со всеми другими переменными.

Пример: f (x, y) 4 + х * у 4

Давайте частично отличаем вышеупомянутые производные в Python W.r.t x

Мы используем Символы Метод, когда количество переменных составляет более 1. Теперь, дифференцируйте производные в Python частично W.R.T Y

Код точно похоже, но теперь Y передается как аргумент ввода в Различать метод.

Мы можем выбрать частично дифференцировать функцию сначала w.r.t x, а затем y.

Заключение

Эта статья ни в коем случае не было дискурсом о производных или как мы можем решать производные в Python, но статью о том, как мы можем использовать пакеты Python для выполнения разграничения на функции. Производные потрясающие, и вы обязательно должны получить идею позади него, так как они играют решающую роль в машинном обучении и за его пределами.

Источник

Derivatives in Python Using Sympy

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

How to calculate derivatives in Python? In this article, we’ll use the Python sympy library to play around with derivatives.

What are derivatives?

Derivatives are the Fundamental tools of Calculus. It is very useful for optimizing a loss function with gradient descent in Machine Learning is possible only because of derivatives.

Suppose we have a function y = f(x) which is dependent on x then the derivation of this function means the rate at which the value y of the function changes with change in x.

This is by no means an article about the fundamentals of derivatives, it can’t be. Calculus is a different beast that requires special attention. I presume you have some background in calculus. This article is intended to demonstrate how we can differentiate a function using the Sympy library.

Solving Derivatives in Python Using Sympy

SymPy is a Python library for symbolic mathematics.

It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible, Cool isn’t it.

1. Install Sympy using PIP

SymPy has more uses than just calculating derivatives but as of now, we’ll focus on derivatives.

Run pip install sympy for installing using the pip package manager.

2. Solving a differential with Sympy diff()

For differentiation, sympy provides us with the diff method to output the derivative of the function.

Let’s see how can we achieve this using sympy.

Declaring a symbol is similar to saying that our function has a variable ‘x’ or simply the function depends on x.

3. Solving derivatives in Python

Now to calculate the derivative of the function at x = 2 sympy has lambdify function in which we pass the symbol and the function.

Basic Derivative Rules in Python sympy

There are certain rules we can use to calculate the derivative of differentiable functions.

Some of the most encountered rules are:

Let’s dive into how can we actually use sympy to calculate derivatives as implied by the general differentiation rules.

1. Power Rule

In general : f'(x n ) = nx (n-1)

Example, Function we have : f(x) = x⁵

It’s derivative will be : f'(x) = 5x (5-1) = 5x 4

2. Product Rule

Let u(x) and v(x) be differentiable functions. Then the product of the functions u(x)v(x) is also differentiable.

Example: f(x) = exp(x)*cos(x)

3. Chain Rule

The chain rule calculate the derivative of a composition of functions.

This process can be extended for quotient rule also. It must be obvious by now that only the function is changing while the application process remains the same, the remaining is taken care of by the library itself.

Derivatives of Multivariable Functions using sympy

The examples we saw above just had one variable. But we are more likely to encounter functions having more than one variable in them. Such derivatives are generally referred to as partial derivative.

A partial derivative of a multivariable function is a derivative with respect to one variable with all other variables held constant.

Example: f(x,y) = x 4 + x * y 4

Let’s partially differentiate the above derivatives in Python w.r.t x

We use symbols method when the number of variables is more than 1. Now, differentiate the derivatives in Python partially w.r.t y

The code is exactly similar but now y is passed as input argument in diff method.

We can choose to partially differentiate function first w.r.t x and then y.

Conclusion

This article by no means was a discourse about derivatives or how can we solve derivatives in Python but an article about how can we leverage python packages to perform differentiation on functions. Derivatives are awesome and you should definitely get the idea behind it as they play a crucial role in Machine learning and beyond.

Источник

Taking Derivatives in Python

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Oct 7, 2019 · 6 min read

The idea behind this post is to revisit some calculus topics needed in data science and machine learning and to take them one step further — calculate them in Python. It’s really simple once you get the gist of it, and you don’t need to worry about memorizing differentiation rules.

This post will be based on a Python library called SymPy, and here’s a short introduction on it ( if you haven’t used it before):

SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python.[1]

To install it ( should come with Anaconda distribution) fire up the terminal window and execute the following:

Differential calculus, Branch of mathematical analysis, devised by Isaac Newton and G.W. Leibniz, and concerned with the problem of finding the rate of change of a function with respect to the variable on which it depends. Thus it involves calculating derivatives and using them to solve problems involving nonconstant rates of change. Typical applications include finding maximum and minimum values of functions in order to solve practical problems in optimization.[2]

And now to be even more specific ( this part will be over soon, I promise), we’ll be calculating derivatives. I don’t remember what those are, either. Nothing fancy, actually:

The derivative of a function at some point characterizes the rate of change of the function at this point. We can estimate the rate of change by calculating the ratio of change of the function Δy to the change of the independent variable Δx. In the definition of derivative, this ratio is considered in the limit as Δx→0.[3]

Okay okay, stop torturing me with the theory already!

This is the last paragraph before diving into examples, honest to God! To start, we’ll dive into single variable functions, but later on, we will go through a couple of examples for multivariate functions, ergo we’ll cover how to calculate partial derivatives. This is something you’ll do more often, I haven’t used derivatives of single-variable functions much in the application part.

Without further ado, let’s get started!

The Derivative of a Single Variable Functions

This would be something covered in your Calc 1 class or online course, involving only functions that deal with single variables, for example, f(x). The goal is to go through some basic differentiation rules, go through them by hand, and then in Python. Let’s get started.

Power Rule

The power rule states this:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Which is pretty self-explanatory, if you listened to some calc class before. If you haven’t, let’s go through a simple example. Your function f(x) is equal to x to the fifth. Now use the power rule to calculate the derivative. It’s pretty straightforward:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Now let’s take a look at how to calculate it in Python. The first thing is to import the library, and then to declare a variable that you will use as a letter in your functions. Here’s how to do it for a single variable function:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Once those cells are executed, it becomes trivial to take the derivative ( same function as above):

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Pay attention to this beautiful print formatting — looks just like an equation written in LaTeX!

Product Rule

The product rule states that if f(x) and g(x) are two differentiable functions, then the derivative is calculated as the first function times the derivative of second plus the second times the derivative of first. That might have sounded confusing a bit when expressed with words, so here’s the notation:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Let’s calculate one example by hand. We have the following:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

As you can see, x squared plus 1 would be f(x), and cosine of x would be g(x). And here’s how you’d do it in Python:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Also straightforward. Make sure to watch where you put those brackets though. Also, note that you can’t use cosine from math or numpy libraries, you need to use the one from sympy.

Chain Rule

If you decide to dive deeper into machine learning algorithms you’ll see chain rule popping up everywhere — gradient descent, backpropagation, you name it. It deals with nested functions, for example, f(g(x)) and states that the derivative is calculated as the derivative of an outer function multiplied with the inner function, then all multiplied by the derivative of the inner function. Here’s the notation:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

And here’s a simple example calculated by hand:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Python implementation is once again as simple as it can be:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

The Derivative of a Multi-Variable Functions

Here, the same rules apply as when dealing with it’s utterly simple single variable brother — you still use the chain rule, power rule, etc, but you take derivatives with respect to one variable while keeping others constant. Oh, and those are called partial derivatives. Fancy.

To start, let’s take the most basic two-variable function and calculate partial derivatives. The function is simply — x squared multiplied by y, and you would differentiate it as follows:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Cool, but how would I do this in Python? Good question. To start, you’ll need to redefine your symbols. And in a traditional Python style, you can do this with one line of code:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

You can here see how the partial derivatives are calculated with respect to x, and then y. Rewriting the function becomes tedious fast, and there’s a way to avoid it. Let’s explore it in the next example.

3 Variable Function

Here’s another example of taking partial derivatives with respect to all 3 variables:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

This will once again require you to alter the symbols:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

And you can be smarter this time and set the function to a variable, instead of rewriting it every time:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

Cool. The remaining part is absolutely the same as before:

Derivative python что это. Смотреть фото Derivative python что это. Смотреть картинку Derivative python что это. Картинка про Derivative python что это. Фото Derivative python что это

This is much more readable. You can even read it literally — differentiate function f with respect to x.

Final Words

This wasn’t an advanced calculus tutorial, heck this even wasn’t a calculus tutorial, and it wasn’t intended to be one. The goal was to point you in the right direction, so you don’t have to take derivatives by hand, or some online calculator.

Try to apply this to linear regression with gradient descent — it would be a good exercise, and I’ll post an article on it in a couple of days.

Want to learn how to take integrals in Python? Let me know.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *