RUВход: насколько изменится потеря
Пусть потеря модели $f(x)=\lVert b-Ax\rVert^2$ зависит от вектора весов $x\in\R^N$. Сдвинем веса на маленький вектор $u$. Насколько изменится потеря? Ответ урока: приблизительно на $Df(x)\,u$, где $Df(x)=-2(b-Ax)^tA$ — одна строка из $N$ чисел. Чтобы получить эту строку честно, лектор начинает с функции одной переменной и шаг за шагом заменяет число матрицей.
Производная через о-малое
Если сильно увеличить график гладкой функции около точки $x_0$, он почти не отличается от прямой. Наклон этой прямой и есть производная: изменение функции равно «наклон × сдвиг» плюс что-то, что намного меньше сдвига.
О-малоеПишут $g(h)=o(h)$ при $h\to0$, если $\lim_{h\to0}\frac{g(h)}{h}=0$: $g$ стремится к нулю быстрее, чем $h$.
Производная как лучшее линейное приближениеЧисло $f'(x_0)$ — производная $f$ в точке $x_0$, если
$$f(x_0+h)-f(x_0)=f'(x_0)\,h+o(h),\qquad h\to0.$$Это то же, что обычное определение: раздели обе части на $h$ и устреми $h\to0$.
Пример. $f(x)=x^2$, $x_0=3$: $f(3+h)-f(3)=9+6h+h^2-9=6h+h^2$. Слагаемое $h^2$ — это $o(h)$, потому что $h^2/h=h\to0$. Значит $f'(3)=6$. При $h=0.01$ изменение равно $0.06+0.0001$: линейная часть даёт почти всё.
Цепное правило лектор пишет в обозначениях Лейбница, $\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}$, — это его любимая запись. Ниже произведение чисел в этой формуле станет произведением матриц.
Зачем это в MLШаг обучения меняет веса на маленький вектор, и потеря меняется почти ровно на линейную часть. Поэтому производная указывает, куда шагать: при малом шаге остаток $o(\cdot)$ пренебрежимо мал.
Теорема Лагранжа о среднем
Если за два часа машина проехала 120 км, то в какой-то момент спидометр показывал ровно 60 км/ч. На графике: хорда между концами отрезка параллельна касательной в некоторой внутренней точке.
Теорема Лагранжа о среднемЕсли $f$ непрерывна на $[a,b]$ и $f'$ существует на $(a,b)$, то найдётся $\xi\in(a,b)$, для которого
$$f(b)-f(a)=f'(\xi)(b-a).$$ Сравни с формулой через о-малое. Там производная взята в известной точке, но есть ошибка $o(h)$. Здесь равенство точное, но точка $\xi$ неизвестна. Известно только, что $\xi$ лежит строго внутри $(a,b)$, — и в доказательстве формулы Тейлора это окажется важным.
Пример. $f(x)=x^2$ на $[1,3]$: $f(3)-f(1)=8$ и $f'(\xi)(3-1)=4\xi$, поэтому $\xi=2$ — внутри отрезка.
Зачем это в MLЕсли $\lvert f'\rvert\le L$ на всём отрезке, теорема даёт $\lvert f(b)-f(a)\rvert\le L\lvert b-a\rvert$: функция не может измениться сильнее. Такие константы (константы Липшица) ограничивают безопасный шаг обучения.
Формула Тейлора с остаточным членом Лагранжа
Линейное приближение использует одну производную. Если добавить вторую, третью и так далее, многочлен повторяет ещё и изгиб графика. Цена — ошибка, и у неё оказывается точная форма, как в теореме о среднем.
Формула Тейлора с остаточным членом в форме ЛагранжаЕсли $f,f',\dots,f^{(N)}$ непрерывны на $[a,b]$, а $f^{(N+1)}$ существует на $(a,b)$, то для некоторого $\xi\in(a,b)$
$$f(b)-f(a)=\sum_{k=1}^{N}\frac{f^{(k)}(a)}{k!}(b-a)^k+\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}.$$Последнее слагаемое — остаточный член. При $N=0$ сумма пуста, и получается теорема о среднем. Если $b<a$, формула верна с $\xi$ строго между $b$ и $a$.
Пример. $f(x)=e^x$, $a=0$, $b=0.1$, $N=2$. Все производные равны $e^x$, в нуле они равны 1, поэтому $e^{0.1}=1+0.1+\frac{0.01}{2}+\frac{e^{\xi}}{6}\cdot0.001=1.105+\frac{e^{\xi}}{6000}$ при $\xi\in(0,0.1)$. Так как $e^{\xi}<e^{0.1}<2$, ошибка многочлена меньше $\frac{2}{6000}\approx0.0003$. Точное значение $e^{0.1}\approx1.10517$: ошибка $0.00017$, оценка выполнена.
Лектор доказал формулу из теоремы о среднем и объяснил зачем: математика — не набор фактов, а теоремы, связанные логикой.
Доказательство в четыре шага
Идея. Заменить $a$ на переменную $x$, построить две вспомогательные функции, которые обращаются в ноль в точке $b$, и применить теорему о среднем к их комбинации.
Шаг 1. Две вспомогательные функции.
$$\varphi(x)=f(b)-\Big\{f(x)+\sum_{k=1}^{N}\frac{f^{(k)}(x)}{k!}(b-x)^k\Big\},\qquad \psi(x)=(b-x)^{N+1}.$$При $x=b$ все степени $(b-x)^k$ равны нулю, поэтому $\varphi(b)=f(b)-f(b)=0$ и $\psi(b)=0$. При $x=a$ получаем $\psi(a)=(b-a)^{N+1}$, а $\varphi(a)$ — это $f(b)$ минус многочлен Тейлора, то есть ровно остаточный член, который нужно найти.
Шаг 2. Производные. $\psi'(x)=-(N+1)(b-x)^N$ по цепному правилу. Для $\varphi$ каждое слагаемое суммы дифференцируется по правилу произведения, и сумма становится телескопической: она имеет вид $(a_N-a_{N-1})+\dots+(a_1-a_0)$, и от неё остаётся только $a_N-a_0$. Итог:
$$\varphi'(x)=-\frac{f^{(N+1)}(x)}{N!}(b-x)^N.$$Промежуточное вычисление — пункт 1 домашнего задания: лектор просил проделать его самостоятельно.
Шаг 3. Вспомогательная функция в духе Коши.
$$F(x)=[\varphi(x)-\varphi(a)][\psi(b)-\psi(a)]-[\varphi(b)-\varphi(a)][\psi(x)-\psi(a)].$$При $x=a$ обе квадратные скобки с $x$ равны нулю, поэтому $F(a)=0$. При $x=b$ два произведения совпадают, поэтому $F(b)=0$. По теореме о среднем $0=F(b)-F(a)=F'(\xi)(b-a)$ для некоторого $\xi\in(a,b)$, то есть
$$\varphi'(\xi)[\psi(b)-\psi(a)]-\psi'(\xi)[\varphi(b)-\varphi(a)]=0.$$Подставим $\psi(b)-\psi(a)=-(b-a)^{N+1}$, $\varphi(b)-\varphi(a)=-\varphi(a)$ и производные из шага 2:
$$\frac{f^{(N+1)}(\xi)}{N!}(b-\xi)^N(b-a)^{N+1}-(N+1)(b-\xi)^N\varphi(a)=0.$$Шаг 4. Сократить на $(b-\xi)^N$. Это законно только потому, что $\xi$ лежит строго внутри $(a,b)$, так что $b-\xi\ne0$. Лектор подчеркнул: даже такая скромная информация о точке полезна. Делим на $(N+1)(b-\xi)^N$:
$$\varphi(a)=\frac{f^{(N+1)}(\xi)}{N!\,(N+1)}(b-a)^{N+1}=\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}.\ ∎$$Ряд Тейлора для $e^x$
При $a=0$ все производные $e^x$ в нуле равны 1, поэтому для любого $b$
$$e^b=\sum_{k=0}^{N}\frac{b^k}{k!}+\frac{e^{\theta}}{(N+1)!}b^{N+1},\qquad \theta\ \text{между}\ 0\ \text{и}\ b.$$Ряд получится, если остаток стремится к нулю при $N\to\infty$. Множитель $e^{\theta}$ не больше $e^{\lvert b\rvert}$ и от $N$ не зависит. Осталось понять, почему $\lvert b\rvert^n/n!\to0$. Довод студента на лекции: запиши $\frac{b^n}{n!}=\frac b1\cdot\frac b2\cdots\frac bn$. Например, при $b=3$ первые три множителя дают $4.5$, а каждый следующий не больше $\frac34$, поэтому $\frac{3^n}{n!}\le4.5\cdot\left(\frac34\right)^{n-3}\to0$. Отсюда $e^x=\sum_{k\ge0}\frac{x^k}{k!}$ для всех $x$: ряд сходится к $e^x$, потому что ошибка конечного многочлена под контролем.
Зачем это в MLМетоды второго порядка (метод Ньютона) приближают потерю многочленом Тейлора степени 2. Квадратичное слагаемое объясняет, почему слишком большой шаг обучения расходится: при большом сдвиге оно перевешивает линейную часть.
Векторы, ковекторы и матрицы
Обозначения лектора, которыми дальше пишется всё:
- $\R^N$ — столбцы высоты $N$; координаты пишутся с верхним индексом: $x=(x^1,\dots,x^N)^t$.
- $M_{m\times n}$ — вещественные матрицы с $m$ строками и $n$ столбцами; элемент $a_{ij}$ стоит в строке $i$, столбце $j$.
- $(\R^N)^*$ — строки, ковекторы: строка $a^t$ берёт столбец $x$ и возвращает число $a^tx$.
- Столбец и строка — просто матрицы с одним столбцом или одной строкой. Число — матрица $1\times1$.
На доске лектор ставит над векторами стрелки ($\vec x$); здесь стрелки опущены, вектор — всегда столбец.
Пример. $a=(1,2)^t$, тогда $a^t$ — ковектор, и $a^tx=x^1+2x^2$ для $x\in\R^2$. Матрица $1\times1$ при транспонировании не меняется: $(a^tx)^t=x^ta=a^tx$. Этот факт решит главную трудность раздела про наименьшие квадраты.
Длина и скалярное произведение матриц
Матрицу $m\times n$ можно читать как длинный вектор из $mn$ чисел. Тогда её длина — корень из суммы квадратов всех элементов, а скалярное произведение — сумма произведений соответствующих элементов.
Длины и скалярное произведение$$\lVert x\rVert=\sqrt{x^tx},\qquad \lVert A\rVert=\sqrt{\tr(A^tA)},\qquad \tr(A^tA)=\sum_{i,j}a_{ij}^2.$$Для $A,B\in M_{m\times n}$ скалярное произведение $\langle A,B\rangle=\tr(A^tB)$. Длина матрицы называется нормой Фробениуса.
Транспонирование здесь нужно: $A^tB$ — квадратная матрица $n\times n$, у неё есть след, и $\langle A,A\rangle\ge0$. Для столбцов формула превращается в привычную $x^ty$, потому что след матрицы $1\times1$ равен ей самой.
Пример. $A=\begin{pmatrix}1&2\\0&3\end{pmatrix}$: $A^tA=\begin{pmatrix}1&0\\2&3\end{pmatrix}\begin{pmatrix}1&2\\0&3\end{pmatrix}=\begin{pmatrix}1&2\\2&13\end{pmatrix}$, след $1+13=14$, и сумма квадратов элементов $1+4+0+9=14$. Значит $\lVert A\rVert=\sqrt{14}$.
Длина даёт расстояние, а расстояние — пределы: «$u\to0$» значит $\lVert u\rVert\to0$.
Цикличность следаЕсли $A\in M_{n\times m}$ и $B\in M_{m\times n}$, то $\tr(AB)=\tr(BA)$. Матрицы не обязаны быть квадратными: $AB$ имеет размер $n\times n$, $BA$ — размер $m\times m$, а следы равны.
Пример. $A=(1\ \ 2)$, $B=(3,4)^t$: $AB=(11)$, след 11; $BA=\begin{pmatrix}3&6\\4&8\end{pmatrix}$, след $3+8=11$.
На доске остались ещё неравенства: $\lVert x+y\rVert\le\lVert x\rVert+\lVert y\rVert$, $\lVert Ax\rVert\le\lVert A\rVert\,\lVert x\rVert$, $\lVert A+B\rVert\le\lVert A\rVert+\lVert B\rVert$, $\lVert AB\rVert\le\lVert A\rVert\,\lVert B\rVert$. Их доказательства и доказательство цикличности — домашнее задание.
Зачем это в MLРегуляризация весов (weight decay) добавляет к потере $\lambda\lVert W\rVert^2$ — квадрат нормы Фробениуса матрицы весов. Неравенство $\lVert Wx\rVert\le\lVert W\rVert\,\lVert x\rVert$ ограничивает, во сколько раз слой может усилить свой вход.
Производная отображения $\R^N\to\R^D$ — матрица $D\times N$
Та же фраза, что для числа: изменение равно линейной части плюс пренебрежимо малое. Только сдвиг теперь — вектор $u\in\R^N$, изменение — вектор из $\R^D$, а «умножить на число» превращается в «умножить на матрицу».
Производная (матрица Якоби)Пусть $f:\R^N\to\R^D$, $y=f(x)$. Производная $f$ в точке $x_0$ — матрица $A\in M_{D\times N}$, для которой
$$f(x_0+u)-f(x_0)=Au+o(\lVert u\rVert),\quad\text{то есть}\quad \lim_{\lVert u\rVert\to0}\frac{f(x_0+u)-f(x_0)-Au}{\lVert u\rVert}=0.$$Обозначение: $Df(x_0)$. Элемент в строке $i$, столбце $j$ равен $\partial f^i/\partial x^j$: строка отвечает компоненте $f^i$, столбец — переменной $x^j$. Обычная производная — матрица $1\times1$, которая оказалась числом.
Пример. $f:\R^3\to\R^2$, $f(x)=\big(x^1x^2,\ x^2+(x^3)^2\big)^t$, $x_0=(1,2,1)^t$. Частные производные:
$$Df(x)=\begin{pmatrix}x^2&x^1&0\\0&1&2x^3\end{pmatrix},\qquad Df(x_0)=\begin{pmatrix}2&1&0\\0&1&2\end{pmatrix}.$$Размер $2\times3$: две компоненты, три переменные.
Два значения слова «якобиан»Иногда «якобианом» называют определитель матрицы Якоби (когда $N=D$). Он нужен для замены переменных в интегралах, а в этом курсе интегралы не рассматриваются. У нас матрица Якоби — это $Df(x_0)$.
Частных производных малоЛектор подчеркнул: существование матрицы $Df(x_0)$ сильнее, чем существование всех частных производных. Пример не из лекции: $f(x^1,x^2)=\frac{x^1x^2}{(x^1)^2+(x^2)^2}$, $f(0,0)=0$ имеет обе частные производные в нуле (они равны 0), но вдоль прямой $x^1=x^2$ равна $\frac12$ и даже не непрерывна в нуле.
Зачем это в MLКаждый слой нейросети — отображение $\R^N\to\R^D$. Его матрица Якоби и есть то, что перемножает обратное распространение ошибки.
Градиент и производная по направлению
Когда $D=1$, матрица $Df(x_0)$ — строка $1\times N$. Градиент — её транспонирование, столбец: $\nabla f(x_0)=Df(x_0)^t$. Лектор настаивал: градиент — вектор, а не ковектор.
Производная по направлениюЕсли $Df(x_0)$ существует, то для любого $u\in\R^N$
$$Df(x_0)\,u=\lim_{h\to0}\frac{f(x_0+hu)-f(x_0)}{h}.$$При $D=1$ это число $\langle\nabla f(x_0),u\rangle$.
Доказательство. При $u=0$ обе части равны нулю. Пусть $u\ne0$. По определению с вектором $hu$ вместо $u$: $f(x_0+hu)-f(x_0)=Df(x_0)(hu)+o(\lVert hu\rVert)$. Делим на $h$:
$$\frac{f(x_0+hu)-f(x_0)}{h}=Df(x_0)u+\frac{o(\lVert hu\rVert)}{\lVert hu\rVert}\cdot\frac{\lVert hu\rVert}{h}.$$Первая дробь стремится к нулю, а модуль второй равен $\lVert u\rVert$ и от $h$ не зависит. Произведение стремится к нулю. ∎
Это главный вычислительный инструмент урока: чтобы найти матрицу $Df(x_0)$, посчитай этот предел для произвольного $u$ и прочитай, что стоит перед $u$.
Пример. $f(x)=(x^1)^2x^2$, $x_0=(1,2)^t$, $u=(1,1)^t$. Частные производные дают $Df(x_0)=(2x^1x^2,\ (x^1)^2)=(4,\ 1)$, и $Df(x_0)u=4+1=5$. Проверка пределом: $f(1+h,2+h)=(1+2h+h^2)(2+h)=2+5h+4h^2+h^3$, значит $\frac{f(x_0+hu)-f(x_0)}{h}=5+4h+h^2\to5$.
Зачем это в MLСреди единичных направлений $u$ число $\langle\nabla f,u\rangle$ меньше всего при $u=-\nabla f/\lVert\nabla f\rVert$ (это Коши — Буняковский). Поэтому градиентный спуск идёт против градиента: это направление быстрейшего убывания.
Цепное правило как произведение матриц
Главный частный случай. Пусть $y=f(u^1,\dots,u^N)$ и $u^j=g^j(t)$, $u_0^j=g^j(t_0)$. Если $Df(u_0)$ существует и все $(g^j)'(t_0)$ существуют, то
$$\left.\frac{dy}{dt}\right|_{t=t_0}=\sum_{j=1}^{N}\frac{\partial f}{\partial u^j}(u_0)\,(g^j)'(t_0).$$Правой части на фото доски нет; это стандартная формула, которая следует из общего вида ниже. Условие — существование всей матрицы $Df(u_0)$, а не только частных производных.
Цепное правилоПусть $G:\R^M\to\R^N$ и $F:\R^N\to\R^D$. Тогда
$$D(F\circ G)(x_0)=DF(G(x_0))\cdot DG(x_0),$$произведение матриц размеров $D\times N$ и $N\times M$, результат — $D\times M$. В координатах: $\frac{\partial y^j}{\partial x^i}=\sum_{k=1}^{N}\frac{\partial y^j}{\partial u^k}\frac{\partial u^k}{\partial x^i}$.
Доказательство лектор дал на следующей лекции (урок m02).
Пример. $G(x)=(x^1+x^2,\ x^1-x^2)^t$, $F(u)=u^1u^2$, $x_0=(2,1)^t$. Тогда $u_0=G(x_0)=(3,1)^t$, $DF(u_0)=(u^2,\ u^1)=(1,\ 3)$, $DG=\begin{pmatrix}1&1\\1&-1\end{pmatrix}$, и
$$D(F\circ G)(x_0)=(1,\ 3)\begin{pmatrix}1&1\\1&-1\end{pmatrix}=(4,\ -2).$$Проверка: $F(G(x))=(x^1)^2-(x^2)^2$, частные производные $2x^1=4$ и $-2x^2=-2$.
Зачем это в MLНейросеть — композиция слоёв. Обратное распространение ошибки перемножает их матрицы Якоби от последнего слоя к первому. В записи $D(F\circ G)=DF\cdot DG$ это слева направо: первой стоит строка производной потери, и после каждого умножения снова получается строка, а не большая матрица.
Пример лектора: наименьшие квадраты
$f(x)=\lVert b-Ax\rVert^2$, $x\in\R^N$, $A\in M_{D\times N}$, $b\in\R^D$ — функция потерь линейной регрессии. Лектор вывел её производную по схеме, которая полностью разобрана в эталонной задаче ниже. Два правила из этого вывода:
- Никогда не дифференцируй длину — дифференцируй квадрат длины. Длина ведёт себя как $\lvert x\rvert$, у которого нет производной в нуле, а квадрат длины — произведение $(b-Ax)^t(b-Ax)$.
- Число равно своему транспонированию. Два средних слагаемых разложения совпадают: $(Au)^t(b-Ax_0)=\big((Au)^t(b-Ax_0)\big)^t=(b-Ax_0)^tAu$.
Результат, обведённый на доске:
$$Df(x_0)=-2(b-Ax_0)^tA,\qquad \nabla f(x_0)=2A^t(Ax_0-b).$$ДополнениеНа этой лекции не прозвучало: приравняв градиент нулю, получаем нормальные уравнения $A^tAx=A^tb$. Это тема урока m02; здесь — чтобы было видно, куда ведёт формула.
Производная по матрице: след и цикличность
Пусть $X\in M_{m\times n}$ — переменная, $a\in\R^m$ и $b\in\R^n$ фиксированы, $f(X)=a^tXb$ — число.
Соглашение лектораПроизводная $Df(X_0)$ — матрица размера $n\times m$, которая действует на сдвиг $U\in M_{m\times n}$ так:
$$Df(X_0)\cdot U=\tr\big(Df(X_0)\,U\big).$$Размер $n\times m$ выбран, чтобы произведение $Df(X_0)\,U$ было квадратным $n\times n$ и имело след.
Предел считается в одну строку, потому что $f$ линейна: $\frac{a^t(X_0+hU)b-a^tX_0b}{h}=a^tUb$. Трудность в другом: $U$ застряла в середине, а умножение матриц некоммутативно, её нельзя просто вынести вправо. Приём лектора — два факта: число равно своему следу, и след цикличен:
$$a^tUb=\tr(a^tUb)=\tr\big((a^tU)\,b\big)=\tr\big(b\,(a^tU)\big)=\tr\big((ba^t)\,U\big).$$Значит $Df(X_0)=ba^t$ — матрица $n\times m$. Её транспонирование $ab^t$ имеет ту же форму, что и $X$; эту форму называют градиентом в библиотеках ML.
Пример. $m=2$, $n=3$, $a=(1,2)^t$, $b=(1,0,1)^t$: $Df(X_0)=ba^t=\begin{pmatrix}1&2\\0&0\\1&2\end{pmatrix}$, размер $3\times2$. Проверка одним элементом: сдвиг $U$ с единицей в строке 1, столбце 1 и нулями в остальных местах даёт $a^tUb=a^1b^1=1$, и $\tr(Df(X_0)\,U)$ равен элементу $Df(X_0)$ в строке 1, столбце 1, то есть тоже 1.
Зачем это в MLВеса слоя — матрица $W$. Чтобы сделать шаг градиентного спуска $W\leftarrow W-\eta G$, нужна матрица $G$ той же формы, что $W$: это транспонированная $Df(W)$. Её библиотеки и хранят рядом с весами.
Что должно остаться в голове
- Производная — лучшее линейное приближение: изменение $=$ линейная часть $+\,o(\cdot)$.
- Теорема о среднем — точное равенство в неизвестной точке $\xi$ строго внутри отрезка.
- Остаточный член Лагранжа $\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}$ даёт гарантированную оценку ошибки многочлена Тейлора.
- Для $f:\R^N\to\R^D$ производная — матрица $D\times N$ частных производных, а градиент $\nabla f=(Df)^t$ — столбец.
- Матрицу $Df(x_0)$ находят через предел $\frac{f(x_0+hu)-f(x_0)}{h}$ и читают коэффициент при $u$.
- Цепное правило: $D(F\circ G)=DF\cdot DG$, размеры $D\times N$ и $N\times M$.
- Длину не дифференцируют — дифференцируют квадрат длины; число равно своему транспонированию.
- Для функции от матрицы: число $=$ его след, цикличность ставит $U$ вправо, $Df(X_0)\in M_{n\times m}$.
ENEntry: how much does the loss change
Let the loss of a model, $f(x)=\lVert b-Ax\rVert^2$, depend on a weight vector $x\in\R^N$. Move the weights by a small vector $u$. How much does the loss change? The answer of this lesson: approximately by $Df(x)\,u$, where $Df(x)=-2(b-Ax)^tA$ is a single row of $N$ numbers. To get this row honestly, the lecturer starts from a function of one variable and replaces the number by a matrix step by step.
The derivative through little-o
Zoom far into the graph of a smooth function near a point $x_0$, and it is almost indistinguishable from a straight line. The slope of that line is the derivative: the change of the function equals “slope × shift” plus something much smaller than the shift.
Little-oWe write $g(h)=o(h)$ as $h\to0$ if $\lim_{h\to0}\frac{g(h)}{h}=0$: $g$ goes to zero faster than $h$.
The derivative as the best linear approximationThe number $f'(x_0)$ is the derivative of $f$ at $x_0$ if
$$f(x_0+h)-f(x_0)=f'(x_0)\,h+o(h),\qquad h\to0.$$This is the usual definition: divide both sides by $h$ and let $h\to0$.
Example. $f(x)=x^2$, $x_0=3$: $f(3+h)-f(3)=9+6h+h^2-9=6h+h^2$. The term $h^2$ is $o(h)$ because $h^2/h=h\to0$. So $f'(3)=6$. For $h=0.01$ the change is $0.06+0.0001$: the linear part gives almost everything.
The lecturer writes the chain rule in Leibniz notation, $\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}$ — the lecturer’s favorite notation. Below, the product of numbers in this formula becomes a product of matrices.
Why this matters for MLA training step moves the weights by a small vector, and the loss changes almost exactly by the linear part. That is why the derivative tells you where to step: for a small step the remainder $o(\cdot)$ is negligible.
The mean value theorem
If a car covered 120 km in two hours, then at some moment its speedometer showed exactly 60 km/h. On the graph: the chord between the endpoints is parallel to the tangent line at some interior point.
Mean value theoremIf $f$ is continuous on $[a,b]$ and $f'$ exists on $(a,b)$, then there is $\xi\in(a,b)$ such that
$$f(b)-f(a)=f'(\xi)(b-a).$$ Compare with the little-o formula. There the derivative is taken at a known point, but there is an error $o(h)$. Here the equality is exact, but the point $\xi$ is unknown. All we know is that $\xi$ lies strictly inside $(a,b)$ — and in the proof of Taylor’s theorem this turns out to matter.
Example. $f(x)=x^2$ on $[1,3]$: $f(3)-f(1)=8$ and $f'(\xi)(3-1)=4\xi$, so $\xi=2$ — inside the interval.
Why this matters for MLIf $\lvert f'\rvert\le L$ on the whole interval, the theorem gives $\lvert f(b)-f(a)\rvert\le L\lvert b-a\rvert$: the function cannot change more than that. Such constants (Lipschitz constants) bound a safe learning step.
Taylor’s theorem with the Lagrange remainder
The linear approximation uses one derivative. Add the second, the third, and so on, and the polynomial also follows the bending of the graph. The price is an error, and it turns out to have an exact form, as in the mean value theorem.
Taylor’s theorem with the Lagrange remainderIf $f,f',\dots,f^{(N)}$ are continuous on $[a,b]$ and $f^{(N+1)}$ exists on $(a,b)$, then for some $\xi\in(a,b)$
$$f(b)-f(a)=\sum_{k=1}^{N}\frac{f^{(k)}(a)}{k!}(b-a)^k+\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}.$$The last term is the remainder. For $N=0$ the sum is empty, and we get the mean value theorem. If $b<a$, the formula holds with $\xi$ strictly between $b$ and $a$.
Example. $f(x)=e^x$, $a=0$, $b=0.1$, $N=2$. All derivatives equal $e^x$, and at zero they equal 1, so $e^{0.1}=1+0.1+\frac{0.01}{2}+\frac{e^{\xi}}{6}\cdot0.001=1.105+\frac{e^{\xi}}{6000}$ with $\xi\in(0,0.1)$. Since $e^{\xi}<e^{0.1}<2$, the error of the polynomial is less than $\frac{2}{6000}\approx0.0003$. The exact value is $e^{0.1}\approx1.10517$: the error is $0.00017$, and the bound holds.
The lecturer proved the theorem from the mean value theorem and explained why: mathematics is not a collection of facts but theorems linked by logic.
The proof in four steps
Idea. Replace $a$ by a variable $x$, build two helper functions that vanish at $b$, and apply the mean value theorem to a combination of them.
Step 1. Two helper functions.
$$\varphi(x)=f(b)-\Big\{f(x)+\sum_{k=1}^{N}\frac{f^{(k)}(x)}{k!}(b-x)^k\Big\},\qquad \psi(x)=(b-x)^{N+1}.$$At $x=b$ all powers $(b-x)^k$ vanish, so $\varphi(b)=f(b)-f(b)=0$ and $\psi(b)=0$. At $x=a$ we get $\psi(a)=(b-a)^{N+1}$, while $\varphi(a)$ is $f(b)$ minus the Taylor polynomial, that is, exactly the remainder we want to find.
Step 2. Derivatives. $\psi'(x)=-(N+1)(b-x)^N$ by the chain rule. For $\varphi$, each term of the sum is differentiated by the product rule, and the sum becomes telescoping: it has the form $(a_N-a_{N-1})+\dots+(a_1-a_0)$, and only $a_N-a_0$ survives. The result:
$$\varphi'(x)=-\frac{f^{(N+1)}(x)}{N!}(b-x)^N.$$The intermediate computation is homework item 1: the lecturer asked you to redo it on your own.
Step 3. A Cauchy-style helper.
$$F(x)=[\varphi(x)-\varphi(a)][\psi(b)-\psi(a)]-[\varphi(b)-\varphi(a)][\psi(x)-\psi(a)].$$At $x=a$ both brackets containing $x$ vanish, so $F(a)=0$. At $x=b$ the two products coincide, so $F(b)=0$. By the mean value theorem $0=F(b)-F(a)=F'(\xi)(b-a)$ for some $\xi\in(a,b)$, that is,
$$\varphi'(\xi)[\psi(b)-\psi(a)]-\psi'(\xi)[\varphi(b)-\varphi(a)]=0.$$Substitute $\psi(b)-\psi(a)=-(b-a)^{N+1}$, $\varphi(b)-\varphi(a)=-\varphi(a)$, and the derivatives from step 2:
$$\frac{f^{(N+1)}(\xi)}{N!}(b-\xi)^N(b-a)^{N+1}-(N+1)(b-\xi)^N\varphi(a)=0.$$Step 4. Cancel $(b-\xi)^N$. This is legal only because $\xi$ lies strictly inside $(a,b)$, so $b-\xi\ne0$. The lecturer stressed it: even this slight information about the point is useful. Divide by $(N+1)(b-\xi)^N$:
$$\varphi(a)=\frac{f^{(N+1)}(\xi)}{N!\,(N+1)}(b-a)^{N+1}=\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}.\ ∎$$The Taylor series of $e^x$
With $a=0$, every derivative of $e^x$ equals 1 at zero, so for any $b$
$$e^b=\sum_{k=0}^{N}\frac{b^k}{k!}+\frac{e^{\theta}}{(N+1)!}b^{N+1},\qquad \theta\ \text{between}\ 0\ \text{and}\ b.$$We get a series if the remainder goes to zero as $N\to\infty$. The factor $e^{\theta}$ is at most $e^{\lvert b\rvert}$ and does not depend on $N$. It remains to see why $\lvert b\rvert^n/n!\to0$. A student’s argument in class: write $\frac{b^n}{n!}=\frac b1\cdot\frac b2\cdots\frac bn$. For example, with $b=3$ the first three factors give $4.5$, and every later factor is at most $\frac34$, so $\frac{3^n}{n!}\le4.5\cdot\left(\frac34\right)^{n-3}\to0$. Hence $e^x=\sum_{k\ge0}\frac{x^k}{k!}$ for all $x$: the series converges to $e^x$ because the error of the finite polynomial is under control.
Why this matters for MLSecond-order methods (Newton’s method) approximate the loss by a Taylor polynomial of degree 2. The quadratic term explains why a learning rate that is too large diverges: for a large shift it outweighs the linear part.
Vectors, covectors, and matrices
The lecturer’s notation, used for everything below:
- $\R^N$ — columns of height $N$; coordinates carry upper indices: $x=(x^1,\dots,x^N)^t$.
- $M_{m\times n}$ — real matrices with $m$ rows and $n$ columns; the entry $a_{ij}$ sits in row $i$, column $j$.
- $(\R^N)^*$ — rows, covectors: a row $a^t$ takes a column $x$ and returns the number $a^tx$.
- A column and a row are just matrices with one column or one row. A number is a $1\times1$ matrix.
On the board the lecturer puts arrows over vectors ($\vec x$); here the arrows are omitted, and a vector is always a column.
Example. $a=(1,2)^t$; then $a^t$ is a covector, and $a^tx=x^1+2x^2$ for $x\in\R^2$. A $1\times1$ matrix does not change under transposition: $(a^tx)^t=x^ta=a^tx$. This fact resolves the main difficulty of the section on least squares.
Length and inner product of matrices
An $m\times n$ matrix can be read as a long vector of $mn$ numbers. Then its length is the square root of the sum of squares of all entries, and the inner product is the sum of products of corresponding entries.
Lengths and inner product$$\lVert x\rVert=\sqrt{x^tx},\qquad \lVert A\rVert=\sqrt{\tr(A^tA)},\qquad \tr(A^tA)=\sum_{i,j}a_{ij}^2.$$For $A,B\in M_{m\times n}$ the inner product is $\langle A,B\rangle=\tr(A^tB)$. The length of a matrix is called the Frobenius norm.
The transpose is needed here: $A^tB$ is a square $n\times n$ matrix, it has a trace, and $\langle A,A\rangle\ge0$. For columns the formula becomes the familiar $x^ty$, because the trace of a $1\times1$ matrix is that matrix itself.
Example. $A=\begin{pmatrix}1&2\\0&3\end{pmatrix}$: $A^tA=\begin{pmatrix}1&0\\2&3\end{pmatrix}\begin{pmatrix}1&2\\0&3\end{pmatrix}=\begin{pmatrix}1&2\\2&13\end{pmatrix}$, the trace is $1+13=14$, and the sum of squares of the entries is $1+4+0+9=14$. So $\lVert A\rVert=\sqrt{14}$.
Length gives distance, and distance gives limits: “$u\to0$” means $\lVert u\rVert\to0$.
Cyclic property of the traceIf $A\in M_{n\times m}$ and $B\in M_{m\times n}$, then $\tr(AB)=\tr(BA)$. The matrices do not have to be square: $AB$ has size $n\times n$, $BA$ has size $m\times m$, and the traces are equal.
Example. $A=(1\ \ 2)$, $B=(3,4)^t$: $AB=(11)$, trace 11; $BA=\begin{pmatrix}3&6\\4&8\end{pmatrix}$, trace $3+8=11$.
The board also listed inequalities: $\lVert x+y\rVert\le\lVert x\rVert+\lVert y\rVert$, $\lVert Ax\rVert\le\lVert A\rVert\,\lVert x\rVert$, $\lVert A+B\rVert\le\lVert A\rVert+\lVert B\rVert$, $\lVert AB\rVert\le\lVert A\rVert\,\lVert B\rVert$. Their proofs and the proof of the cyclic property are homework.
Why this matters for MLWeight decay adds $\lambda\lVert W\rVert^2$ to the loss — the squared Frobenius norm of the weight matrix. The inequality $\lVert Wx\rVert\le\lVert W\rVert\,\lVert x\rVert$ bounds how much a layer can amplify its input.
The derivative of a map $\R^N\to\R^D$ is a $D\times N$ matrix
The same sentence as for numbers: the change equals the linear part plus something negligible. Only now the shift is a vector $u\in\R^N$, the change is a vector in $\R^D$, and “multiply by a number” becomes “multiply by a matrix”.
Derivative (Jacobian matrix)Let $f:\R^N\to\R^D$, $y=f(x)$. The derivative of $f$ at $x_0$ is a matrix $A\in M_{D\times N}$ such that
$$f(x_0+u)-f(x_0)=Au+o(\lVert u\rVert),\quad\text{that is,}\quad \lim_{\lVert u\rVert\to0}\frac{f(x_0+u)-f(x_0)-Au}{\lVert u\rVert}=0.$$Notation: $Df(x_0)$. The entry in row $i$, column $j$ is $\partial f^i/\partial x^j$: the row belongs to the component $f^i$, the column to the variable $x^j$. An ordinary derivative is a $1\times1$ matrix that happens to be a number.
Example. $f:\R^3\to\R^2$, $f(x)=\big(x^1x^2,\ x^2+(x^3)^2\big)^t$, $x_0=(1,2,1)^t$. Partial derivatives:
$$Df(x)=\begin{pmatrix}x^2&x^1&0\\0&1&2x^3\end{pmatrix},\qquad Df(x_0)=\begin{pmatrix}2&1&0\\0&1&2\end{pmatrix}.$$Size $2\times3$: two components, three variables.
Two meanings of “Jacobian”Sometimes “the Jacobian” means the determinant of the Jacobian matrix (when $N=D$). It is used for changes of variables in integrals, and this course does not cover integrals. For us the Jacobian matrix is $Df(x_0)$.
Partial derivatives are not enoughThe lecturer stressed: the existence of the matrix $Df(x_0)$ is stronger than the existence of all partial derivatives. An example not from the lecture: $f(x^1,x^2)=\frac{x^1x^2}{(x^1)^2+(x^2)^2}$, $f(0,0)=0$ has both partial derivatives at zero (both equal 0), but along the line $x^1=x^2$ it equals $\frac12$ and is not even continuous at zero.
Why this matters for MLEach layer of a neural network is a map $\R^N\to\R^D$. Its Jacobian matrix is exactly what backpropagation multiplies.
Gradient and directional derivative
When $D=1$, the matrix $Df(x_0)$ is a $1\times N$ row. The gradient is its transpose, a column: $\nabla f(x_0)=Df(x_0)^t$. The lecturer insisted: the gradient is a vector, not a covector.
Directional derivativeIf $Df(x_0)$ exists, then for every $u\in\R^N$
$$Df(x_0)\,u=\lim_{h\to0}\frac{f(x_0+hu)-f(x_0)}{h}.$$For $D=1$ this is the number $\langle\nabla f(x_0),u\rangle$.
Proof. For $u=0$ both sides are zero. Let $u\ne0$. By the definition with the vector $hu$ in place of $u$: $f(x_0+hu)-f(x_0)=Df(x_0)(hu)+o(\lVert hu\rVert)$. Divide by $h$:
$$\frac{f(x_0+hu)-f(x_0)}{h}=Df(x_0)u+\frac{o(\lVert hu\rVert)}{\lVert hu\rVert}\cdot\frac{\lVert hu\rVert}{h}.$$The first fraction goes to zero, and the absolute value of the second equals $\lVert u\rVert$ and does not depend on $h$. The product goes to zero. ∎
This is the main computing tool of the lesson: to find the matrix $Df(x_0)$, compute this limit for an arbitrary $u$ and read off what multiplies $u$.
Example. $f(x)=(x^1)^2x^2$, $x_0=(1,2)^t$, $u=(1,1)^t$. Partial derivatives give $Df(x_0)=(2x^1x^2,\ (x^1)^2)=(4,\ 1)$, and $Df(x_0)u=4+1=5$. Check by the limit: $f(1+h,2+h)=(1+2h+h^2)(2+h)=2+5h+4h^2+h^3$, so $\frac{f(x_0+hu)-f(x_0)}{h}=5+4h+h^2\to5$.
Why this matters for MLAmong unit directions $u$, the number $\langle\nabla f,u\rangle$ is smallest at $u=-\nabla f/\lVert\nabla f\rVert$ (this is Cauchy–Schwarz). That is why gradient descent moves against the gradient: it is the direction of fastest decrease.
The chain rule as a matrix product
The essential special case. Let $y=f(u^1,\dots,u^N)$ and $u^j=g^j(t)$, $u_0^j=g^j(t_0)$. If $Df(u_0)$ exists and all $(g^j)'(t_0)$ exist, then
$$\left.\frac{dy}{dt}\right|_{t=t_0}=\sum_{j=1}^{N}\frac{\partial f}{\partial u^j}(u_0)\,(g^j)'(t_0).$$The right-hand side is not on the board photo; it is the standard formula, and it follows from the general form below. The condition is the existence of the whole matrix $Df(u_0)$, not only of the partial derivatives.
Chain ruleLet $G:\R^M\to\R^N$ and $F:\R^N\to\R^D$. Then
$$D(F\circ G)(x_0)=DF(G(x_0))\cdot DG(x_0),$$a product of matrices of sizes $D\times N$ and $N\times M$; the result is $D\times M$. In coordinates: $\frac{\partial y^j}{\partial x^i}=\sum_{k=1}^{N}\frac{\partial y^j}{\partial u^k}\frac{\partial u^k}{\partial x^i}$.
The lecturer gave the proof in the next lecture (lesson m02).
Example. $G(x)=(x^1+x^2,\ x^1-x^2)^t$, $F(u)=u^1u^2$, $x_0=(2,1)^t$. Then $u_0=G(x_0)=(3,1)^t$, $DF(u_0)=(u^2,\ u^1)=(1,\ 3)$, $DG=\begin{pmatrix}1&1\\1&-1\end{pmatrix}$, and
$$D(F\circ G)(x_0)=(1,\ 3)\begin{pmatrix}1&1\\1&-1\end{pmatrix}=(4,\ -2).$$Check: $F(G(x))=(x^1)^2-(x^2)^2$, with partial derivatives $2x^1=4$ and $-2x^2=-2$.
Why this matters for MLA neural network is a composition of layers. Backpropagation multiplies their Jacobian matrices from the last layer to the first. In the notation $D(F\circ G)=DF\cdot DG$ this is left to right: the row of the loss derivative comes first, and after each multiplication you again get a row rather than a large matrix.
The lecturer’s example: least squares
$f(x)=\lVert b-Ax\rVert^2$, $x\in\R^N$, $A\in M_{D\times N}$, $b\in\R^D$ — the loss of linear regression. The lecturer derived its derivative by the scheme that is worked out in full in the model problem below. Two rules from that derivation:
- Never differentiate a length; differentiate the squared length. A length behaves like $\lvert x\rvert$, which has no derivative at zero, while the squared length is a product $(b-Ax)^t(b-Ax)$.
- A number equals its own transpose. The two middle terms of the expansion coincide: $(Au)^t(b-Ax_0)=\big((Au)^t(b-Ax_0)\big)^t=(b-Ax_0)^tAu$.
The result, boxed on the board:
$$Df(x_0)=-2(b-Ax_0)^tA,\qquad \nabla f(x_0)=2A^t(Ax_0-b).$$Not from the lectureNot said in this lecture: setting the gradient to zero gives the normal equations $A^tAx=A^tb$. That is the topic of lesson m02; it is mentioned here to show where the formula leads.
Derivative with respect to a matrix: trace and cyclic property
Let $X\in M_{m\times n}$ be the variable, $a\in\R^m$ and $b\in\R^n$ fixed, and $f(X)=a^tXb$ a number.
The lecturer’s conventionThe derivative $Df(X_0)$ is an $n\times m$ matrix that acts on a shift $U\in M_{m\times n}$ as follows:
$$Df(X_0)\cdot U=\tr\big(Df(X_0)\,U\big).$$The size $n\times m$ is chosen so that the product $Df(X_0)\,U$ is a square $n\times n$ matrix and has a trace.
The limit takes one line because $f$ is linear: $\frac{a^t(X_0+hU)b-a^tX_0b}{h}=a^tUb$. The difficulty is elsewhere: $U$ is trapped in the middle, and matrix multiplication is not commutative, so you cannot simply move it to the right. The lecturer’s trick uses two facts: a number equals its own trace, and the trace is cyclic:
$$a^tUb=\tr(a^tUb)=\tr\big((a^tU)\,b\big)=\tr\big(b\,(a^tU)\big)=\tr\big((ba^t)\,U\big).$$So $Df(X_0)=ba^t$, an $n\times m$ matrix. Its transpose $ab^t$ has the same shape as $X$; ML libraries call this shape-matched form the gradient.
Example. $m=2$, $n=3$, $a=(1,2)^t$, $b=(1,0,1)^t$: $Df(X_0)=ba^t=\begin{pmatrix}1&2\\0&0\\1&2\end{pmatrix}$, size $3\times2$. Check one entry: the shift $U$ with a one in row 1, column 1 and zeros elsewhere gives $a^tUb=a^1b^1=1$, and $\tr(Df(X_0)\,U)$ equals the entry of $Df(X_0)$ in row 1, column 1, which is also 1.
Why this matters for MLThe weights of a layer form a matrix $W$. To take a gradient descent step $W\leftarrow W-\eta G$, you need a matrix $G$ of the same shape as $W$: it is the transposed $Df(W)$. That is what libraries store next to the weights.
What should stay with you
- The derivative is the best linear approximation: change $=$ linear part $+\,o(\cdot)$.
- The mean value theorem is an exact equality at an unknown point $\xi$ strictly inside the interval.
- The Lagrange remainder $\frac{f^{(N+1)}(\xi)}{(N+1)!}(b-a)^{N+1}$ gives a guaranteed error bound for a Taylor polynomial.
- For $f:\R^N\to\R^D$ the derivative is the $D\times N$ matrix of partial derivatives, and the gradient $\nabla f=(Df)^t$ is a column.
- The matrix $Df(x_0)$ is found through the limit $\frac{f(x_0+hu)-f(x_0)}{h}$ by reading off the coefficient of $u$.
- Chain rule: $D(F\circ G)=DF\cdot DG$, with sizes $D\times N$ and $N\times M$.
- Do not differentiate a length — differentiate the squared length; a number equals its own transpose.
- For a function of a matrix: a number $=$ its trace, the cyclic property moves $U$ to the right, $Df(X_0)\in M_{n\times m}$.