RUВход: одна функция, два способа
Возьми матрицу $A = \begin{pmatrix}1&3\\1&2\end{pmatrix}$ и функцию двух переменных $f(x) = x^tAx$, где $x = (x^1,x^2)^t$. Раскроем произведение: $Ax = (x^1+3x^2,\ x^1+2x^2)^t$, и
$$f(x) = x^1(x^1+3x^2) + x^2(x^1+2x^2) = (x^1)^2 + 4x^1x^2 + 2(x^2)^2.$$Вопрос урока: как быстро меняется $f$ в точке $x_0 = (1,1)^t$, если двигать только $x^1$? А если только $x^2$? Ответ — два числа, $6$ и $8$. К концу урока ты получишь их двумя независимыми путями: частными производными по формуле и одним матричным умножением $(A+A^t)x_0$. По дороге понадобятся размеры при умножении, правило транспонирования, след и частные производные — ровно то, на чём стоят лекции math-01 и math-02.
ОбозначенияКак у лектора: транспонирование $A^t$; $M_{m\times n}$ — матрицы из $m$ строк и $n$ столбцов; векторы — столбцы; координаты с верхним индексом, $x^1$ — это первая координата, а не степень. Степень координаты пишется со скобками: $(x^1)^2$. В днях Полигона (день 10, день 18) транспонирование записано заглавной буквой T, а векторы — строками; в ML-школе так не пишем.
Размеры и произведение матриц
Картинка: элемент произведения $AB$ в строке $i$, столбце $j$ — это скалярное произведение строки $i$ матрицы $A$ на столбец $j$ матрицы $B$. Чтобы оно существовало, длина строки $A$ должна совпасть с высотой столбца $B$.
Произведение матрицПусть $A\in M_{m\times n}$, $B\in M_{n\times k}$. Тогда $AB\in M_{m\times k}$ и
$$(AB)_{ij} = \sum_{s=1}^{n} a_{is}b_{sj},\qquad i = 1,\dots,m,\quad j = 1,\dots,k.$$Правило размеров: $(m\times n)(n\times k) = m\times k$ — внутренние размеры совпадают и исчезают, внешние остаются.
Пример. $A = \begin{pmatrix}1&2\\0&-1\\3&1\end{pmatrix}\in M_{3\times2}$ и $x = (2,1)^t\in M_{2\times1}$. Размеры: $(3\times2)(2\times1) = 3\times1$, значит, ответ — столбец из трёх чисел:
$$Ax = \begin{pmatrix}1\cdot2+2\cdot1\\0\cdot2+(-1)\cdot1\\3\cdot2+1\cdot1\end{pmatrix} = \begin{pmatrix}4\\-1\\7\end{pmatrix}.$$Произведение $xA$ не определено: в $(2\times1)(3\times2)$ внутренние размеры $1$ и $3$ не совпадают.
Порядок множителейДаже когда существуют оба произведения $AB$ и $BA$, они обычно различны и могут иметь разные размеры: для $A\in M_{2\times3}$, $B\in M_{3\times2}$ матрица $AB$ имеет размер $2\times2$, а $BA$ — размер $3\times3$. Перед каждым умножением подписывай размеры под множителями. Эта проверка занимает пять секунд.
Строка — это матрица $1\times N$, столбец — матрица $N\times1$. Поэтому для $x,y\in\R^N$ произведение $x^ty$ имеет размер $(1\times N)(N\times1) = 1\times1$ — это одно число $x^1y^1+\dots+x^Ny^N$, а $xy^t$ имеет размер $(N\times1)(1\times N) = N\times N$ — это целая матрица, внешнее произведение.
Зачем это в MLЛинейный слой нейросети — это $y = Wx$ с $W\in M_{D\times N}$: на входе $N$ признаков, на выходе $D$ чисел. Значительная часть ошибок в коде моделей — несовпавшие размеры, и ловятся они ровно правилом $(m\times n)(n\times k)$.
Транспонирование произведения
Транспонирование отражает таблицу относительно главной диагонали: $(A^t)_{ij} = a_{ji}$, строки становятся столбцами. Если $A\in M_{m\times n}$, то $A^t\in M_{n\times m}$.
Почему у произведения меняется порядок? Размеры подсказывают ответ раньше формулы. Пусть $A\in M_{m\times n}$, $B\in M_{n\times k}$; тогда $(AB)^t\in M_{k\times m}$. Из $A^t\in M_{n\times m}$ и $B^t\in M_{k\times n}$ матрицу размера $k\times m$ можно получить только как $B^tA^t$; произведение $A^tB^t$ при $m\ne k$ даже не определено.
Правила транспонирования$$(A^t)^t = A,\qquad (A+B)^t = A^t+B^t,\qquad (\lambda A)^t = \lambda A^t,\qquad (AB)^t = B^tA^t.$$Для трёх множителей порядок разворачивается целиком: $(ABC)^t = C^tB^tA^t$.
Почему $(AB)^t = B^tA^t$. Сравним элементы в строке $i$, столбце $j$:
$$\big((AB)^t\big)_{ij} = (AB)_{ji} = \sum_{s} a_{js}b_{si} = \sum_{s} b_{si}a_{js} = \sum_{s} (B^t)_{is}(A^t)_{sj} = (B^tA^t)_{ij}.$$Третье равенство — перестановка двух чисел в каждом слагаемом, четвёртое — запись $b_{si} = (B^t)_{is}$ и $a_{js} = (A^t)_{sj}$.
Число равно своему транспонированию. Матрица $1\times1$ при транспонировании не меняется. Лектор пользуется этим постоянно: для $A\in M_{D\times N}$, $u\in\R^N$, $v\in\R^D$
$$v^tAu = (v^tAu)^t = u^tA^t(v^t)^t = u^tA^tv.$$Пример. $u = (1,2)^t$, $v = (1,0,1)^t$, а $A\in M_{3\times2}$ — та же, что в примере выше. Тогда $Au = (1+4,\ 0-2,\ 3+2)^t = (5,-2,5)^t$, и $v^tAu = 5+0+5 = 10$. С другой стороны, $A^tv = (1+3,\ 2+1)^t = (4,3)^t$, и $u^tA^tv = 4+6 = 10$ ✓.
Где теряют транспонированиеВ числе $x^tAu$ нельзя просто поменять местами $x$ и $u$: $x^tAu = u^tA^tx$, а не $u^tAx$. Эти два числа совпадают, только если $A = A^t$. В задаче f0114 именно это отличает верный ответ от неверного.
Зачем это в MLВ выводе градиента функции потерь линейной регрессии (лекция math-01) два средних слагаемых $(Au)^t(b-Ax_0)$ и $(b-Ax_0)^tAu$ сводятся в одно ровно этим приёмом. Отсюда множитель $2$ в $\nabla f = 2A^t(Ax_0-b)$.
След и цикличность
Картинка: у квадратной матрицы есть диагональ из левого верхнего угла в правый нижний. След — сумма чисел на ней. Неожиданное свойство следа в том, что ему безразличен порядок двух множителей, хотя самим произведениям — нет.
След и цикличностьДля квадратной $C\in M_{n\times n}$ след — сумма диагональных элементов: $\tr C = c_{11}+c_{22}+\dots+c_{nn}$. Для $A\in M_{m\times n}$ и $B\in M_{n\times m}$ обе матрицы $AB\in M_{m\times m}$ и $BA\in M_{n\times n}$ квадратные, и
$$\tr(AB) = \tr(BA).$$Сами $A$ и $B$ не обязаны быть квадратными; размеры $AB$ и $BA$ при этом разные, а следы равны.
Свойство цикличности сформулировано на лекции math-01 (доска 15). Его доказательство — пункт 4 домашнего задания HW-M01, поэтому здесь доказательства нет: урок учит пользоваться свойством и проверять его на числах.
Пример. $A = \begin{pmatrix}1&2&0\\0&1&1\end{pmatrix}\in M_{2\times3}$, $B = \begin{pmatrix}1&0\\2&1\\0&3\end{pmatrix}\in M_{3\times2}$. Для следа нужны только диагональные элементы. У $AB$ ($2\times2$): $(AB)_{11} = 1\cdot1+2\cdot2+0\cdot0 = 5$, $(AB)_{22} = 0\cdot0+1\cdot1+1\cdot3 = 4$, так что $\tr(AB) = 9$. У $BA$ ($3\times3$): $(BA)_{11} = 1\cdot1+0\cdot0 = 1$, $(BA)_{22} = 2\cdot2+1\cdot1 = 5$, $(BA)_{33} = 0\cdot0+3\cdot1 = 3$, так что $\tr(BA) = 9$ ✓.
Три следствия, которыми пользуются чаще самого свойства.
- Число равно своему следу: для матрицы $1\times1$ выполнено $\tr c = c$.
- Множители можно прокручивать по кругу: $\tr(ABC) = \tr(CAB) = \tr(BCA)$. Первое равенство — это $\tr(XY) = \tr(YX)$ при $X = AB$, $Y = C$; второе — то же при $X = CA$, $Y = B$: $\tr\big((CA)B\big) = \tr\big(B(CA)\big)$. Переставлять множители произвольно нельзя: $\tr(ABC)$ и $\tr(ACB)$ в общем случае различны.
- Вектор на конце можно перенести в начало: для $u,v\in\R^N$ выполнено $\tr(uv^t) = \tr(v^tu) = v^tu$. Слева след матрицы $N\times N$, справа одно скалярное произведение.
На лекции math-01 так получен ответ для $f(X) = a^tXb$: матрица $U$ «зажата» посередине, и её выводят в конец:
$$a^tUb = \tr(a^tUb) = \tr\big((a^tU)\,b\big) = \tr\big(b\,(a^tU)\big) = \tr\big((ba^t)\,U\big).$$Зачем это в MLВеса нейросети — матрицы, и производная функции потерь по матрице весов вычисляется именно так: число записывают как след и прокручивают множители, пока изменение $U$ не окажется справа. Отсюда $Df(X_0) = ba^t$.
Производная сложной функции одной переменной
Картинка: $y$ зависит от $u$, а $u$ зависит от $x$. Сдвинь $x$ на малое $h$: $u$ сдвинется примерно на $g'(x_0)\,h$, а $y$ — примерно на $f'(u_0)\cdot g'(x_0)\,h$. Скорости перемножаются.
Цепное правилоПусть $u = g(x)$ дифференцируема в точке $x_0$, а $y = f(u)$ дифференцируема в точке $u_0 = g(x_0)$. Тогда $y = f(g(x))$ дифференцируема в $x_0$ и
$$\frac{dy}{dx}\Big|_{x_0} = f'(u_0)\,g'(x_0),\qquad\text{в обозначениях Лейбница}\qquad \frac{dy}{dx} = \frac{dy}{du}\cdot\frac{du}{dx}.$$ Пример. $y = (1+\sin x)^3$ в точке $x = 0$. Слои: $y = u^3$, $u = 1+\sin x$. Значение внутреннего слоя: $u_0 = 1+\sin0 = 1$. Производные: $\frac{dy}{du} = 3u^2 = 3$ при $u_0 = 1$ и $\frac{du}{dx} = \cos x = 1$ при $x = 0$. Итог: $\frac{dy}{dx} = 3\cdot1 = 3$. Если слоёв три, множителей тоже три, и каждая производная берётся в значении своего внутреннего слоя.
Две ошибки цепного правилаПервая — забыть внутреннюю производную: $\big(\sin(x^2)\big)' = \cos(x^2)\cdot2x$, а не $\cos(x^2)$. Вторая — взять производную внешнего слоя не в той точке: $f'$ считается в $u_0 = g(x_0)$, а не в $x_0$. Проверка: перед дифференцированием выпиши значения всех слоёв в точке.
Зачем это в MLДаже один нейрон $y = \sigma(wx+b)$ — сложная функция: $\frac{\partial y}{\partial w} = \sigma'(wx+b)\cdot x$. Обратное распространение ошибки — это то же цепное правило, применённое слой за слоем справа налево.
Частные производные и градиент
Картинка: график $z = f(x^1,x^2)$ — поверхность над плоскостью. Разрежь её вертикальной плоскостью $x^2 = \text{const}$: получится кривая, и наклон этой кривой — частная производная по $x^1$. Двигаешь одну координату, остальные стоят на месте.
Частная производнаяДля $f:\R^N\to\R$ и точки $x_0$ частная производная по $x^i$ —
$$\frac{\partial f}{\partial x^i}(x_0) = \lim_{h\to0}\frac{f(x_0+he_i)-f(x_0)}{h},$$где $e_i$ — столбец с единицей на месте $i$ и нулями на остальных местах. Считается она как обычная производная по $x^i$, когда все остальные координаты считаются числами.
Пример из входа. $f = (x^1)^2 + 4x^1x^2 + 2(x^2)^2$. По $x^1$, считая $x^2$ числом: $\frac{\partial f}{\partial x^1} = 2x^1 + 4x^2$, в точке $(1,1)^t$ это $6$. По $x^2$, считая $x^1$ числом: $\frac{\partial f}{\partial x^2} = 4x^1 + 4x^2$, в точке это $8$.
Пример со сложной функцией. $f(x^1,x^2) = \ln\big(1+(x^1)^2x^2\big)$. По $x^1$ — цепное правило одной переменной, $x^2$ стоит как число: $\frac{\partial f}{\partial x^1} = \frac{2x^1x^2}{1+(x^1)^2x^2}$; в точке $(1,1)^t$ это $\frac{2}{2} = 1$.
ГрадиентСтрока частных производных — это матрица производной $Df(x_0) = \Big(\frac{\partial f}{\partial x^1}(x_0),\ \dots,\ \frac{\partial f}{\partial x^N}(x_0)\Big)$ размера $1\times N$. Градиент — её транспонирование, столбец: $\nabla f(x_0) = Df(x_0)^t$.
Лектор подчеркнул на math-01: если $Df(x_0)$ существует, то её элементы — частные производные, но одно существование всех частных производных слабее существования $Df(x_0)$.
ДополнениеНе из лекции, но снимает этот вопрос для всех задач урока: если частные производные непрерывны в окрестности точки, то $Df$ в этой точке существует. У многочленов, $\sin$, $\cos$, $e^x$ и $\ln$ в области определения частные производные непрерывны.
Градиент квадратичной формы. Почему в примере входа получилось $(A+A^t)x_0$? Раскроем $f(x_0+hu) = (x_0+hu)^tA(x_0+hu)$, пользуясь $(x_0+hu)^t = x_0^t + hu^t$:
$$f(x_0+hu) = x_0^tAx_0 + h\,x_0^tAu + h\,u^tAx_0 + h^2\,u^tAu.$$Число $x_0^tAu$ равно своему транспонированию $u^tA^tx_0$, поэтому коэффициент при $h$ равен $u^tA^tx_0 + u^tAx_0 = u^t(A+A^t)x_0$. По предложению лекции math-01 о производной по направлению предел $\frac{f(x_0+hu)-f(x_0)}{h}$ при $h\to0$ равен $Df(x_0)\,u$, значит, $Df(x_0)\,u = \big((A+A^t)x_0\big)^tu$ для любого $u$, и
$$\nabla(x^tAx) = (A+A^t)x.$$Проверка на входе: $A + A^t = \begin{pmatrix}2&4\\4&4\end{pmatrix}$, и $(A+A^t)(1,1)^t = (6,8)^t$ — те же $6$ и $8$ ✓.
Зачем это в MLКвадратичная функция потерь — простейшая модель того, что происходит около минимума любой гладкой функции потерь. Шаг градиентного спуска $w\leftarrow w - \eta\nabla L(w)$ требует ровно этого: столбца частных производных в текущей точке. Задача f0119 делает такой шаг целиком.
Вторые и смешанные производные
Частная производная $\partial f/\partial x^i$ — снова функция тех же переменных, и её можно дифференцировать ещё раз.
Вторые производные$$\frac{\partial^2 f}{\partial x^j\,\partial x^i} = \frac{\partial}{\partial x^j}\Big(\frac{\partial f}{\partial x^i}\Big),\qquad \frac{\partial^2 f}{\partial (x^i)^2} = \frac{\partial}{\partial x^i}\Big(\frac{\partial f}{\partial x^i}\Big).$$Читается справа налево: сначала по $x^i$ (переменная, стоящая ближе к $f$), потом результат по $x^j$. Так же записаны производные $g''(t)$ на доске лекции math-02.
Пример. $f(x,y) = x^2y^3$. Первые производные: $\frac{\partial f}{\partial x} = 2xy^3$, $\frac{\partial f}{\partial y} = 3x^2y^2$. Вторые: $\frac{\partial^2 f}{\partial x^2} = 2y^3$, $\frac{\partial^2 f}{\partial y^2} = 6x^2y$, $\frac{\partial^2 f}{\partial x\,\partial y} = \frac{\partial}{\partial x}(3x^2y^2) = 6xy^2$ и $\frac{\partial^2 f}{\partial y\,\partial x} = \frac{\partial}{\partial y}(2xy^3) = 6xy^2$. Смешанные совпали.
Дополнение: теорема ШварцаНе из лекции; нужна для гессиана и лапласиана. Если все вторые частные производные $f$ непрерывны в окрестности точки, то в этой точке $\frac{\partial^2 f}{\partial x\,\partial y} = \frac{\partial^2 f}{\partial y\,\partial x}$. Порядок дифференцирования тогда не важен, но писать его всё равно нужно аккуратно: это проверка, что ничего не пропущено.
Две конструкции из вторых производных встретятся в курсе сразу. Гессиан — матрица $H$ с элементами $H_{ij} = \frac{\partial^2 f}{\partial x^i\,\partial x^j}$. Для функции из входа $\frac{\partial^2 f}{\partial (x^1)^2} = 2$, $\frac{\partial^2 f}{\partial x^1\,\partial x^2} = 4$, $\frac{\partial^2 f}{\partial (x^2)^2} = 4$, то есть $H = \begin{pmatrix}2&4\\4&4\end{pmatrix} = A + A^t$. Лапласиан функции двух переменных — $\Delta f = \frac{\partial^2 f}{\partial x^2} + \frac{\partial^2 f}{\partial y^2}$, сумма диагонали гессиана. Например, $\Delta(x^2-y^2) = 2-2 = 0$, а $\Delta(x^2+y^2) = 2+2 = 4$.
Правило произведения во второй производнойЕсли первая производная — произведение, например $\frac{\partial}{\partial y}\sin(xy) = x\cos(xy)$, то при дифференцировании по $x$ оба множителя зависят от $x$. Нужно правило произведения: два слагаемых, а не одно.
Зачем это в MLГессиан описывает кривизну функции потерь. Слишком большой шаг градиентного спуска для данной кривизны перепрыгивает минимум, а методы второго порядка (метод Ньютона) используют гессиан напрямую.
Цепное правило для нескольких переменных и замена переменных
Картинка: $t$ сдвигается на $\Delta t$, каждая $u^j$ сдвигается примерно на $g_j'(t_0)\,\Delta t$, и каждый такой сдвиг меняет $f$ примерно на $\frac{\partial f}{\partial u^j}\,g_j'(t_0)\,\Delta t$. Вклады складываются.
Цепное правило (лекция math-01)Пусть $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)$ существуют. Тогда
$$\frac{dy}{dt}\Big|_{t_0} = \sum_{j=1}^{N}\frac{\partial f}{\partial u^j}(u_0)\,g_j'(t_0).$$В общем виде $D(F\circ G) = DF\cdot DG$ — произведение матриц.
Правая часть этой формулы на фото доски не попала; в конспекте она восстановлена как стандартная, и в таком же виде её доказывали на лекции math-02.
Пример. $y = (u^1)^2u^2$, $u^1 = \cos t$, $u^2 = \sin t$, точка $t = 0$. Значения: $u_0 = (1,0)^t$. Частные производные в $u_0$: $\frac{\partial f}{\partial u^1} = 2u^1u^2 = 0$, $\frac{\partial f}{\partial u^2} = (u^1)^2 = 1$. Производные слоёв: $g_1'(0) = -\sin0 = 0$, $g_2'(0) = \cos0 = 1$. Итог: $\frac{dy}{dt} = 0\cdot0 + 1\cdot1 = 1$. Проверка подстановкой: $y = \cos^2t\sin t$, $y' = -2\cos t\sin^2t + \cos^3t$, при $t = 0$ это $1$ ✓.
Замена переменных. Если $x = x(u,v)$, $y = y(u,v)$ и $g(u,v) = f\big(x(u,v),y(u,v)\big)$, то частная производная по $u$ — то же цепное правило, только $v$ заморожена:
$$\frac{\partial g}{\partial u} = \frac{\partial f}{\partial x}\frac{\partial x}{\partial u} + \frac{\partial f}{\partial y}\frac{\partial y}{\partial u}.$$Для полярных координат $x = r\cos\theta$, $y = r\sin\theta$ это формулы с доски лекции math-02 (там, как у лектора, одной буквой $f$ обозначена и функция от $x,y$, и она же как функция от $r,\theta$):
$$\frac{\partial f}{\partial r} = \frac{\partial f}{\partial x}\cos\theta + \frac{\partial f}{\partial y}\sin\theta,\qquad \frac{\partial f}{\partial\theta} = \frac{\partial f}{\partial x}(-r\sin\theta) + \frac{\partial f}{\partial y}\,r\cos\theta.$$Вторые производные после замены — главное место урока. В формуле для $\frac{\partial g}{\partial u}$ стоят $\frac{\partial f}{\partial x}$ и $\frac{\partial f}{\partial y}$, взятые в точке $\big(x(u,v),y(u,v)\big)$. Это снова сложные функции от $u$ и $v$. Поэтому при втором дифференцировании по $u$ работают два правила сразу:
- Цепное правило заново для каждой частной производной $f$: $\frac{\partial}{\partial u}\Big(\frac{\partial f}{\partial x}\Big) = \frac{\partial^2 f}{\partial x^2}\frac{\partial x}{\partial u} + \frac{\partial^2 f}{\partial y\,\partial x}\frac{\partial y}{\partial u}$.
- Правило произведения, если коэффициенты $\frac{\partial x}{\partial u}$, $\frac{\partial y}{\partial u}$ сами зависят от $u$: тогда появляется ещё слагаемое $\frac{\partial f}{\partial x}\frac{\partial^2 x}{\partial u^2}$ (и такое же для $y$).
Как это выглядит на конкретной функции, показывает эталонная задача ниже.
Что теряют во второй производнойЧаще всего теряют одно из двух: что $\frac{\partial f}{\partial x}$ зависит от $u$ через $x$ и $y$ (тогда пропадают вторые производные $f$), или что коэффициент вроде $\cos\theta$ или $r$ тоже надо дифференцировать (тогда пропадают первые производные $f$). Проверка: подставь конкретную функцию, например $f = x^2y$, и сравни с прямым счётом.
Зачем это в MLНормировка признака $x = (x'-\mu)/\sigma$ — это замена переменной, и по цепному правилу $\frac{\partial L}{\partial x'} = \frac{\partial L}{\partial x}\cdot\frac{1}{\sigma}$: масштаб признака напрямую меняет масштаб градиента. Та же схема в новом базисе — это полярные и сферические координаты из HW-M02.
Что должно остаться в голове
- $(m\times n)(n\times k) = m\times k$: подписывай размеры под каждым множителем.
- $(AB)^t = B^tA^t$; число равно своему транспонированию, поэтому $x^tAu = u^tA^tx$.
- $\tr(AB) = \tr(BA)$ и для неквадратных $A$, $B$; число равно своему следу; $\tr(uv^t) = v^tu$.
- Цепное правило: производная внешнего слоя в значении внутреннего, умноженная на производную внутреннего.
- Частная производная: заморозь остальные переменные; градиент — столбец; $\nabla(x^tAx) = (A+A^t)x$.
- $\frac{\partial^2 f}{\partial x^j\,\partial x^i}$ — сначала по $x^i$, потом по $x^j$; при непрерывных вторых производных порядок не важен.
- После замены переменных частная производная $f$ — снова сложная функция: второе дифференцирование — цепное правило заново плюс правило произведения.
ENEntry: one function, two routes
Take the matrix $A = \begin{pmatrix}1&3\\1&2\end{pmatrix}$ and the function of two variables $f(x) = x^tAx$, where $x = (x^1,x^2)^t$. Expand the product: $Ax = (x^1+3x^2,\ x^1+2x^2)^t$, and
$$f(x) = x^1(x^1+3x^2) + x^2(x^1+2x^2) = (x^1)^2 + 4x^1x^2 + 2(x^2)^2.$$The question of the lesson: how fast does $f$ change at the point $x_0 = (1,1)^t$ if only $x^1$ moves? And if only $x^2$ moves? The answer is two numbers, $6$ and $8$. By the end of the lesson you get them by two independent routes: partial derivatives of the formula, and a single matrix product $(A+A^t)x_0$. On the way you need sizes in a product, the transpose rule, the trace, and partial derivatives — exactly what lectures math-01 and math-02 stand on.
NotationAs the lecturer writes it: the transpose is $A^t$; $M_{m\times n}$ is the set of matrices with $m$ rows and $n$ columns; vectors are columns; components carry upper indices, so $x^1$ is the first component, not a power. A power of a component is written with parentheses: $(x^1)^2$. In the Poligon days (day 10, day 18) the transpose is written with a capital T and vectors as rows; the ML School does not write them that way.
Sizes and the matrix product
The picture: the entry of $AB$ in row $i$, column $j$ is the dot product of row $i$ of $A$ with column $j$ of $B$. For it to exist, the length of a row of $A$ must equal the height of a column of $B$.
Matrix productLet $A\in M_{m\times n}$, $B\in M_{n\times k}$. Then $AB\in M_{m\times k}$ and
$$(AB)_{ij} = \sum_{s=1}^{n} a_{is}b_{sj},\qquad i = 1,\dots,m,\quad j = 1,\dots,k.$$The size rule: $(m\times n)(n\times k) = m\times k$ — the inner sizes match and disappear, the outer ones remain.
Example. $A = \begin{pmatrix}1&2\\0&-1\\3&1\end{pmatrix}\in M_{3\times2}$ and $x = (2,1)^t\in M_{2\times1}$. Sizes: $(3\times2)(2\times1) = 3\times1$, so the answer is a column of three numbers:
$$Ax = \begin{pmatrix}1\cdot2+2\cdot1\\0\cdot2+(-1)\cdot1\\3\cdot2+1\cdot1\end{pmatrix} = \begin{pmatrix}4\\-1\\7\end{pmatrix}.$$The product $xA$ is undefined: in $(2\times1)(3\times2)$ the inner sizes $1$ and $3$ do not match.
Order of the factorsEven when both products $AB$ and $BA$ exist, they are usually different and can have different sizes: for $A\in M_{2\times3}$, $B\in M_{3\times2}$ the matrix $AB$ has size $2\times2$, and $BA$ has size $3\times3$. Before every product, write the sizes under the factors. This check takes five seconds.
A row is a $1\times N$ matrix, a column is an $N\times1$ matrix. So for $x,y\in\R^N$ the product $x^ty$ has size $(1\times N)(N\times1) = 1\times1$ — it is one number $x^1y^1+\dots+x^Ny^N$, while $xy^t$ has size $(N\times1)(1\times N) = N\times N$ — it is a whole matrix, the outer product.
Why this matters for MLA linear layer of a neural network is $y = Wx$ with $W\in M_{D\times N}$: $N$ features in, $D$ numbers out. A large share of bugs in model code are mismatched sizes, and they are caught by exactly the rule $(m\times n)(n\times k)$.
Transpose of a product
The transpose reflects the table across the main diagonal: $(A^t)_{ij} = a_{ji}$, rows become columns. If $A\in M_{m\times n}$, then $A^t\in M_{n\times m}$.
Why does the order change for a product? The sizes give the answer before the formula does. Let $A\in M_{m\times n}$, $B\in M_{n\times k}$; then $(AB)^t\in M_{k\times m}$. From $A^t\in M_{n\times m}$ and $B^t\in M_{k\times n}$ a matrix of size $k\times m$ can only be obtained as $B^tA^t$; the product $A^tB^t$ is not even defined when $m\ne k$.
Transpose rules$$(A^t)^t = A,\qquad (A+B)^t = A^t+B^t,\qquad (\lambda A)^t = \lambda A^t,\qquad (AB)^t = B^tA^t.$$For three factors the order reverses completely: $(ABC)^t = C^tB^tA^t$.
Why $(AB)^t = B^tA^t$. Compare the entries in row $i$, column $j$:
$$\big((AB)^t\big)_{ij} = (AB)_{ji} = \sum_{s} a_{js}b_{si} = \sum_{s} b_{si}a_{js} = \sum_{s} (B^t)_{is}(A^t)_{sj} = (B^tA^t)_{ij}.$$The third equality swaps two numbers in each term; the fourth writes $b_{si} = (B^t)_{is}$ and $a_{js} = (A^t)_{sj}$.
A number equals its own transpose. A $1\times1$ matrix does not change under transposition. The lecturer uses this all the time: for $A\in M_{D\times N}$, $u\in\R^N$, $v\in\R^D$
$$v^tAu = (v^tAu)^t = u^tA^t(v^t)^t = u^tA^tv.$$Example. $u = (1,2)^t$, $v = (1,0,1)^t$, and $A\in M_{3\times2}$ is the same as in the example above. Then $Au = (1+4,\ 0-2,\ 3+2)^t = (5,-2,5)^t$, and $v^tAu = 5+0+5 = 10$. On the other side, $A^tv = (1+3,\ 2+1)^t = (4,3)^t$, and $u^tA^tv = 4+6 = 10$ ✓.
Where the transpose gets lostIn the number $x^tAu$ you cannot simply swap $x$ and $u$: $x^tAu = u^tA^tx$, not $u^tAx$. These two numbers coincide only if $A = A^t$. In problem f0114 this is exactly what separates the right answer from a wrong one.
Why this matters for MLIn the derivation of the gradient of the linear regression loss (lecture math-01) the two middle terms $(Au)^t(b-Ax_0)$ and $(b-Ax_0)^tAu$ merge into one by exactly this trick. That is where the factor $2$ in $\nabla f = 2A^t(Ax_0-b)$ comes from.
Trace and the cyclic property
The picture: a square matrix has a diagonal from the top-left corner to the bottom-right one. The trace is the sum of the numbers on it. The unexpected property of the trace is that it does not care about the order of two factors, even though the products themselves do.
Trace and the cyclic propertyFor a square $C\in M_{n\times n}$ the trace is the sum of the diagonal entries: $\tr C = c_{11}+c_{22}+\dots+c_{nn}$. For $A\in M_{m\times n}$ and $B\in M_{n\times m}$ both matrices $AB\in M_{m\times m}$ and $BA\in M_{n\times n}$ are square, and
$$\tr(AB) = \tr(BA).$$$A$ and $B$ themselves need not be square; $AB$ and $BA$ then have different sizes, but equal traces.
The cyclic property was stated in lecture math-01 (board 15). Its proof is item 4 of homework HW-M01, so there is no proof here: the lesson teaches you to use the property and to check it on numbers.
Example. $A = \begin{pmatrix}1&2&0\\0&1&1\end{pmatrix}\in M_{2\times3}$, $B = \begin{pmatrix}1&0\\2&1\\0&3\end{pmatrix}\in M_{3\times2}$. The trace needs only the diagonal entries. For $AB$ ($2\times2$): $(AB)_{11} = 1\cdot1+2\cdot2+0\cdot0 = 5$, $(AB)_{22} = 0\cdot0+1\cdot1+1\cdot3 = 4$, so $\tr(AB) = 9$. For $BA$ ($3\times3$): $(BA)_{11} = 1\cdot1+0\cdot0 = 1$, $(BA)_{22} = 2\cdot2+1\cdot1 = 5$, $(BA)_{33} = 0\cdot0+3\cdot1 = 3$, so $\tr(BA) = 9$ ✓.
Three consequences that are used more often than the property itself.
- A number equals its own trace: for a $1\times1$ matrix, $\tr c = c$.
- Factors can be rotated around the cycle: $\tr(ABC) = \tr(CAB) = \tr(BCA)$. The first equality is $\tr(XY) = \tr(YX)$ with $X = AB$, $Y = C$; the second is the same with $X = CA$, $Y = B$: $\tr\big((CA)B\big) = \tr\big(B(CA)\big)$. Factors cannot be permuted arbitrarily: $\tr(ABC)$ and $\tr(ACB)$ are different in general.
- A vector at the end can be moved to the front: for $u,v\in\R^N$, $\tr(uv^t) = \tr(v^tu) = v^tu$. On the left is the trace of an $N\times N$ matrix, on the right a single dot product.
This is how lecture math-01 got the answer for $f(X) = a^tXb$: the matrix $U$ is “trapped” in the middle, and it is moved to the end:
$$a^tUb = \tr(a^tUb) = \tr\big((a^tU)\,b\big) = \tr\big(b\,(a^tU)\big) = \tr\big((ba^t)\,U\big).$$Why this matters for MLThe weights of a neural network are matrices, and the derivative of a loss with respect to a weight matrix is computed exactly like this: write the number as a trace and rotate the factors until the change $U$ stands on the right. Hence $Df(X_0) = ba^t$.
Derivative of a composite function of one variable
The picture: $y$ depends on $u$, and $u$ depends on $x$. Move $x$ by a small $h$: $u$ moves by about $g'(x_0)\,h$, and $y$ by about $f'(u_0)\cdot g'(x_0)\,h$. The rates multiply.
Chain ruleLet $u = g(x)$ be differentiable at the point $x_0$, and $y = f(u)$ be differentiable at the point $u_0 = g(x_0)$. Then $y = f(g(x))$ is differentiable at $x_0$ and
$$\frac{dy}{dx}\Big|_{x_0} = f'(u_0)\,g'(x_0),\qquad\text{in Leibniz notation}\qquad \frac{dy}{dx} = \frac{dy}{du}\cdot\frac{du}{dx}.$$ Example. $y = (1+\sin x)^3$ at the point $x = 0$. Layers: $y = u^3$, $u = 1+\sin x$. The value of the inner layer: $u_0 = 1+\sin0 = 1$. Derivatives: $\frac{dy}{du} = 3u^2 = 3$ at $u_0 = 1$ and $\frac{du}{dx} = \cos x = 1$ at $x = 0$. Result: $\frac{dy}{dx} = 3\cdot1 = 3$. With three layers there are three factors, and each derivative is taken at the value of its own inner layer.
Two chain rule mistakesThe first is forgetting the inner derivative: $\big(\sin(x^2)\big)' = \cos(x^2)\cdot2x$, not $\cos(x^2)$. The second is taking the derivative of the outer layer at the wrong point: $f'$ is evaluated at $u_0 = g(x_0)$, not at $x_0$. The check: before differentiating, write down the values of all layers at the point.
Why this matters for MLEven a single neuron $y = \sigma(wx+b)$ is a composite function: $\frac{\partial y}{\partial w} = \sigma'(wx+b)\cdot x$. Backpropagation is the same chain rule applied layer by layer, from right to left.
Partial derivatives and the gradient
The picture: the graph $z = f(x^1,x^2)$ is a surface over the plane. Cut it with the vertical plane $x^2 = \text{const}$: you get a curve, and the slope of that curve is the partial derivative with respect to $x^1$. One coordinate moves, the others stay put.
Partial derivativeFor $f:\R^N\to\R$ and a point $x_0$, the partial derivative with respect to $x^i$ is
$$\frac{\partial f}{\partial x^i}(x_0) = \lim_{h\to0}\frac{f(x_0+he_i)-f(x_0)}{h},$$where $e_i$ is the column with a one in place $i$ and zeros elsewhere. It is computed as an ordinary derivative in $x^i$, with all other components treated as numbers.
Example from the entry. $f = (x^1)^2 + 4x^1x^2 + 2(x^2)^2$. In $x^1$, treating $x^2$ as a number: $\frac{\partial f}{\partial x^1} = 2x^1 + 4x^2$, which is $6$ at $(1,1)^t$. In $x^2$, treating $x^1$ as a number: $\frac{\partial f}{\partial x^2} = 4x^1 + 4x^2$, which is $8$ at the point.
Example with a composite function. $f(x^1,x^2) = \ln\big(1+(x^1)^2x^2\big)$. In $x^1$ this is the one-variable chain rule, with $x^2$ standing as a number: $\frac{\partial f}{\partial x^1} = \frac{2x^1x^2}{1+(x^1)^2x^2}$; at $(1,1)^t$ this is $\frac{2}{2} = 1$.
GradientThe row of partial derivatives is the derivative matrix $Df(x_0) = \Big(\frac{\partial f}{\partial x^1}(x_0),\ \dots,\ \frac{\partial f}{\partial x^N}(x_0)\Big)$ of size $1\times N$. The gradient is its transpose, a column: $\nabla f(x_0) = Df(x_0)^t$.
The lecturer stressed in math-01: if $Df(x_0)$ exists, its entries are the partial derivatives, but the mere existence of all partial derivatives is weaker than the existence of $Df(x_0)$.
Not from the lectureAdded because it settles this question for every problem of the lesson: if the partial derivatives are continuous near the point, then $Df$ exists at that point. Polynomials, $\sin$, $\cos$, $e^x$, and $\ln$ have continuous partial derivatives on their domains.
Gradient of a quadratic form. Why did the entry example give $(A+A^t)x_0$? Expand $f(x_0+hu) = (x_0+hu)^tA(x_0+hu)$, using $(x_0+hu)^t = x_0^t + hu^t$:
$$f(x_0+hu) = x_0^tAx_0 + h\,x_0^tAu + h\,u^tAx_0 + h^2\,u^tAu.$$The number $x_0^tAu$ equals its own transpose $u^tA^tx_0$, so the coefficient of $h$ is $u^tA^tx_0 + u^tAx_0 = u^t(A+A^t)x_0$. By the proposition on directional derivatives from lecture math-01, the limit of $\frac{f(x_0+hu)-f(x_0)}{h}$ as $h\to0$ equals $Df(x_0)\,u$, so $Df(x_0)\,u = \big((A+A^t)x_0\big)^tu$ for every $u$, and
$$\nabla(x^tAx) = (A+A^t)x.$$Check on the entry: $A + A^t = \begin{pmatrix}2&4\\4&4\end{pmatrix}$, and $(A+A^t)(1,1)^t = (6,8)^t$ — the same $6$ and $8$ ✓.
Why this matters for MLA quadratic loss is the simplest model of what happens near the minimum of any smooth loss. A gradient descent step $w\leftarrow w - \eta\nabla L(w)$ needs exactly this: the column of partial derivatives at the current point. Problem f0119 takes such a step from start to finish.
Second and mixed derivatives
The partial derivative $\partial f/\partial x^i$ is again a function of the same variables, and it can be differentiated once more.
Second derivatives$$\frac{\partial^2 f}{\partial x^j\,\partial x^i} = \frac{\partial}{\partial x^j}\Big(\frac{\partial f}{\partial x^i}\Big),\qquad \frac{\partial^2 f}{\partial (x^i)^2} = \frac{\partial}{\partial x^i}\Big(\frac{\partial f}{\partial x^i}\Big).$$Read it from right to left: first in $x^i$ (the variable closer to $f$), then the result in $x^j$. The derivatives $g''(t)$ on the board of lecture math-02 are written the same way.
Example. $f(x,y) = x^2y^3$. First derivatives: $\frac{\partial f}{\partial x} = 2xy^3$, $\frac{\partial f}{\partial y} = 3x^2y^2$. Second: $\frac{\partial^2 f}{\partial x^2} = 2y^3$, $\frac{\partial^2 f}{\partial y^2} = 6x^2y$, $\frac{\partial^2 f}{\partial x\,\partial y} = \frac{\partial}{\partial x}(3x^2y^2) = 6xy^2$ and $\frac{\partial^2 f}{\partial y\,\partial x} = \frac{\partial}{\partial y}(2xy^3) = 6xy^2$. The mixed derivatives coincide.
Not from the lecture: Schwarz’s theoremAdded because the Hessian and the Laplacian need it. If all second partial derivatives of $f$ are continuous near a point, then at that point $\frac{\partial^2 f}{\partial x\,\partial y} = \frac{\partial^2 f}{\partial y\,\partial x}$. The order of differentiation then does not matter, but still write it carefully: it is a check that nothing was skipped.
Two constructions made of second derivatives appear in the course right away. The Hessian is the matrix $H$ with entries $H_{ij} = \frac{\partial^2 f}{\partial x^i\,\partial x^j}$. For the entry function $\frac{\partial^2 f}{\partial (x^1)^2} = 2$, $\frac{\partial^2 f}{\partial x^1\,\partial x^2} = 4$, $\frac{\partial^2 f}{\partial (x^2)^2} = 4$, that is, $H = \begin{pmatrix}2&4\\4&4\end{pmatrix} = A + A^t$. The Laplacian of a function of two variables is $\Delta f = \frac{\partial^2 f}{\partial x^2} + \frac{\partial^2 f}{\partial y^2}$, the sum of the diagonal of the Hessian. For example, $\Delta(x^2-y^2) = 2-2 = 0$, and $\Delta(x^2+y^2) = 2+2 = 4$.
The product rule in a second derivativeIf the first derivative is a product, for example $\frac{\partial}{\partial y}\sin(xy) = x\cos(xy)$, then both factors depend on $x$ when you differentiate in $x$. You need the product rule: two terms, not one.
Why this matters for MLThe Hessian describes the curvature of the loss. A gradient descent step that is too large for that curvature jumps over the minimum, and second-order methods (Newton’s method) use the Hessian directly.
Multivariable chain rule and change of variables
The picture: $t$ moves by $\Delta t$, each $u^j$ moves by about $g_j'(t_0)\,\Delta t$, and each such move changes $f$ by about $\frac{\partial f}{\partial u^j}\,g_j'(t_0)\,\Delta t$. The contributions add up.
Chain rule (lecture math-01)Let $y = f(u^1,\dots,u^N)$, $u^j = g_j(t)$, $u_0^j = g_j(t_0)$, let the matrix $Df(u_0)$ exist, and let all $g_j'(t_0)$ exist. Then
$$\frac{dy}{dt}\Big|_{t_0} = \sum_{j=1}^{N}\frac{\partial f}{\partial u^j}(u_0)\,g_j'(t_0).$$In general form, $D(F\circ G) = DF\cdot DG$ — a product of matrices.
The right-hand side of this formula is not on the board photo; the lesson notes reconstruct it as the standard formula, and lecture math-02 proved it in this same form.
Example. $y = (u^1)^2u^2$, $u^1 = \cos t$, $u^2 = \sin t$, the point $t = 0$. Values: $u_0 = (1,0)^t$. Partial derivatives at $u_0$: $\frac{\partial f}{\partial u^1} = 2u^1u^2 = 0$, $\frac{\partial f}{\partial u^2} = (u^1)^2 = 1$. Derivatives of the layers: $g_1'(0) = -\sin0 = 0$, $g_2'(0) = \cos0 = 1$. Result: $\frac{dy}{dt} = 0\cdot0 + 1\cdot1 = 1$. Check by substitution: $y = \cos^2t\sin t$, $y' = -2\cos t\sin^2t + \cos^3t$, which is $1$ at $t = 0$ ✓.
Change of variables. If $x = x(u,v)$, $y = y(u,v)$, and $g(u,v) = f\big(x(u,v),y(u,v)\big)$, then the partial derivative in $u$ is the same chain rule with $v$ frozen:
$$\frac{\partial g}{\partial u} = \frac{\partial f}{\partial x}\frac{\partial x}{\partial u} + \frac{\partial f}{\partial y}\frac{\partial y}{\partial u}.$$For polar coordinates $x = r\cos\theta$, $y = r\sin\theta$ these are the formulas from the board of lecture math-02 (there, as the lecturer does, one letter $f$ denotes both the function of $x,y$ and the same function of $r,\theta$):
$$\frac{\partial f}{\partial r} = \frac{\partial f}{\partial x}\cos\theta + \frac{\partial f}{\partial y}\sin\theta,\qquad \frac{\partial f}{\partial\theta} = \frac{\partial f}{\partial x}(-r\sin\theta) + \frac{\partial f}{\partial y}\,r\cos\theta.$$Second derivatives after a change of variables — the central point of the lesson. The formula for $\frac{\partial g}{\partial u}$ contains $\frac{\partial f}{\partial x}$ and $\frac{\partial f}{\partial y}$ evaluated at the point $\big(x(u,v),y(u,v)\big)$. These are again composite functions of $u$ and $v$. So when you differentiate in $u$ a second time, two rules work at once:
- The chain rule again for each partial derivative of $f$: $\frac{\partial}{\partial u}\Big(\frac{\partial f}{\partial x}\Big) = \frac{\partial^2 f}{\partial x^2}\frac{\partial x}{\partial u} + \frac{\partial^2 f}{\partial y\,\partial x}\frac{\partial y}{\partial u}$.
- The product rule, if the coefficients $\frac{\partial x}{\partial u}$, $\frac{\partial y}{\partial u}$ themselves depend on $u$: then one more term appears, $\frac{\partial f}{\partial x}\frac{\partial^2 x}{\partial u^2}$ (and the same one for $y$).
The model problem below shows how this looks on a concrete function.
What gets lost in a second derivativeMost often one of two things is lost: that $\frac{\partial f}{\partial x}$ depends on $u$ through $x$ and $y$ (then the second derivatives of $f$ disappear), or that a coefficient such as $\cos\theta$ or $r$ also has to be differentiated (then the first derivatives of $f$ disappear). The check: substitute a concrete function, for example $f = x^2y$, and compare with direct computation.
Why this matters for MLNormalizing a feature, $x = (x'-\mu)/\sigma$, is a change of variables, and by the chain rule $\frac{\partial L}{\partial x'} = \frac{\partial L}{\partial x}\cdot\frac{1}{\sigma}$: the scale of a feature directly changes the scale of the gradient. The same scheme in a new basis is the polar and spherical coordinates of HW-M02.
What should stay with you
- $(m\times n)(n\times k) = m\times k$: write the sizes under every factor.
- $(AB)^t = B^tA^t$; a number equals its own transpose, so $x^tAu = u^tA^tx$.
- $\tr(AB) = \tr(BA)$ also for non-square $A$, $B$; a number equals its own trace; $\tr(uv^t) = v^tu$.
- Chain rule: the derivative of the outer layer at the value of the inner one, times the derivative of the inner one.
- Partial derivative: freeze the other variables; the gradient is a column; $\nabla(x^tAx) = (A+A^t)x$.
- $\frac{\partial^2 f}{\partial x^j\,\partial x^i}$ means first in $x^i$, then in $x^j$; with continuous second derivatives the order does not matter.
- After a change of variables a partial derivative of $f$ is again a composite function: the second differentiation is the chain rule again plus the product rule.