## 2020年4月25日土曜日

### 数学 - Python - 解析学 - 多変数の関数 - 合成微分律と勾配ベクトル - ノルム、偏微分、指数関数、対数関数

1. $X=\left({x}_{1},\dots ,{x}_{n}\right)$

とおく。

このとき、

$\begin{array}{l}r\\ =∥X∥\\ =\sqrt{\sum _{k=1}^{n}{x}_{k}^{2}}\end{array}$

求める勾配ベクトルは

$\begin{array}{l}gradf\left(X\right)=\left({D}_{1}f\left(X\right),\dots ,{D}_{n.}f\left(X\right)\right)\\ {D}_{k}f\left(X\right)\\ =\frac{d}{{\mathrm{dx}}_{k}}f\left(X\right)\\ =\frac{d}{{\mathrm{dx}}_{k}}g\left(r\right)\\ =\frac{d}{{\mathrm{dx}}_{k}}·\frac{1}{r}\\ =-\frac{1}{{r}^{2}}·\frac{{x}_{k}}{\sqrt{\sum _{k=1}^{n}{x}_{k}^{2}}}\\ =-\frac{{x}_{k}}{{r}^{3}}\\ gradf\left(X\right)=-\frac{X}{{r}^{3}}\end{array}$

2. $\begin{array}{l}gradf\left(X\right)\\ =gradg\left(r\right)\\ =grad{r}^{2}\\ =\left(2r\frac{{x}_{1}}{r},\dots ,2r\frac{{x}_{n}}{r}\right)\\ =2X\end{array}$

3. $\begin{array}{l}\frac{d}{{\mathrm{dx}}_{k}}\frac{1}{{r}^{3}}\\ =-\frac{3{r}^{2}}{{r}^{6}}-\frac{{x}_{k}}{r}\\ =-\frac{3{x}_{k}}{{r}^{5}}\\ gradf\left(X\right)=-\frac{3X}{{r}^{5}}\end{array}$

4. $\begin{array}{l}\frac{d}{{\mathrm{dx}}_{k}}{e}^{-{r}^{2}}\\ =-2r{e}^{-{r}^{2}}·\frac{{x}_{k}}{r}\\ =-2{e}^{-{r}^{2}}{x}_{k}\\ gradf\left(X\right)=-2{e}^{-{r}^{2}}X\end{array}$

5. $\begin{array}{l}\frac{d}{{\mathrm{dx}}_{k}}\mathrm{log}\frac{1}{r}\\ =-r·\frac{1}{{r}^{2}}\frac{{x}_{k}}{r}\\ =-\frac{{x}_{k}}{{r}^{2}}\\ gradf\left(X\right)=-\frac{X}{{r}^{2}}\end{array}$

6. $\begin{array}{l}\frac{d}{{\mathrm{dx}}_{k}}\frac{4}{{r}^{m}}\\ =-\frac{4·m{r}^{m-1}}{{r}^{2m}}·\frac{{x}_{k}}{r}\\ =-\frac{4m{x}_{k}}{{r}^{m+2}}\\ gradf\left(X\right)=-\frac{4mX}{{r}^{m+2}}\end{array}$

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import symbols, Function, Matrix, exp, log

print('9.')

xs = symbols('x:5', real=True)
X = Matrix(xs)
r = X.norm()
m = symbols('m', integer=True)
fs = [1 / r, r ** 2, 1 / r ** 3, exp(-r ** 2), log(1 / r), 4 / r ** m]
gradfs = [Matrix([f.diff(x, 1) for x in xs])
for f in fs]

class TestDerivativeChainRule(TestCase):
def test_a(self):
self.assertEqual(gradfs[0], - X / r ** 3)

def test_b(self):

def test_c(self):
self.assertEqual(gradfs[2], -3 * X / r ** 5)

def test_d(self):
self.assertEqual(gradfs[3], -2 * exp(-r ** 2) * X)

def test_e(self):
self.assertEqual(gradfs[4], -X / r ** 2)

def test_f(self):
for m0 in range(-10, 11):
if m == 1:
continue
-4 * m0 * X/r ** (m0 + 2))

if __name__ == "__main__":
main()


% ./sample9.py -v
9.
test_a (__main__.TestDerivativeChainRule) ... ok
test_b (__main__.TestDerivativeChainRule) ... ok
test_c (__main__.TestDerivativeChainRule) ... ok
test_d (__main__.TestDerivativeChainRule) ... ok
test_e (__main__.TestDerivativeChainRule) ... ok
test_f (__main__.TestDerivativeChainRule) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.087s

OK
%