Минимизируйте функцию вручную в Python
Реализуйте градиентный спуск на простой кривой
«Минимизируйте функцию вручную в Python» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
A Tiny Practice Problem
Let's run gradient descent ourselves on one simple curve. We will minimize a basic function in plain Python before trusting any framework to do it.
Pick a Function
We use a single-dip parabola. Its lowest point sits at x equal to 3, so that is the minimum our code should discover on its own.
def f(x):
return (x - 3) ** 2Know the Gradient
For this curve the slope, or gradient, is two times x minus three. In real models autograd computes this for you, but here we write it directly.
def grad(x):
return 2 * (x - 3)Start Somewhere
Descent needs a starting point. We pick an arbitrary initial value far from the answer so we can watch the steps march toward it.
x = 0.0Choose a Learning Rate
We set a modest learning rate so steps are big enough to make progress but small enough to avoid overshooting the dip.
lr = 0.1The Update Step
Each iteration applies the same rule from before: subtract the scaled gradient from x. One line does all the downhill work.
x = x - lr * grad(x)Loop It
One step is not enough, so we wrap the update in a loop. Twenty or so iterations let x slide steadily toward the minimum.
for i in range(20):
x = x - lr * grad(x)Watch It Converge
Print x and f(x) each pass and you will see them converge: x creeps toward 3 and the function value shrinks toward zero.
print(round(x, 4), round(f(x), 6))Steps Get Smaller
Notice the moves shrink as you approach the bottom. Near the minimum the gradient is tiny, so each step naturally slows down without any extra code.
Try a Bad Rate
Set the learning rate to something like 1.1 and rerun. x bounces away instead of settling, showing live how a too-big step diverges.
lr = 1.1Same Idea, Bigger Scale
This handful of lines is exactly what deep learning does, just with millions of weights and an automatic gradient. The core loop never changes.
Quick Check
What signals that descent is converging?
Recap
You coded gradient descent by hand: define a function and its gradient, start somewhere, then loop the update rule until x converges on the minimum. ✅
Часто задаваемые вопросы
Урок «Минимизируйте функцию вручную в Python» бесплатный?
Да — полный текст урока «Минимизируйте функцию вручную в Python» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Минимизируйте функцию вручную в Python»?
Реализуйте градиентный спуск на простой кривой Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Минимизируйте функцию вручную в Python»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Функция потерь как ландшафт для спуска
- Градиенты указывают вверх — поэтому двигайтесь в обратную сторону
- Скорость обучения: слишком большая, слишком малая или оптимальная
- Минимизируйте функцию вручную в Python