開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の7章(初等解析問題を解く)、7.10(プログラミングチャレンジ)、問題7-2(勾配降下法を実装する)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3 from sympy import Derivative, symbols, sympify, SympifyError import matplotlib.pyplot as plt def grad_descent(x0, f1x, x): epsilon = 1e-6 step_size = 1e-4 x_old = x0 x_new = x_old - step_size * f1x.subs({x: x_old}).evalf() xs = [] while abs(x_old - x_new) > epsilon: xs.append(x_new) x_old = x_new x_new = x_old - step_size * f1x.subs({x: x_old}).evalf() return x_new, xs def find_min_theta(R, theta): R1theta = Derivative(R, theta).doit() theta0 = 1e-3 theta_min = grad_descent(theta0, R1theta, theta) return theta_min def draw(f, var, xs): xs0 = [] i = -1 while i < 1: xs0.append(i) i += 0.01 ys0 = [f.subs({var: x}) for x in xs0] plt.plot(xs0, ys0, 'g.') ys = [f.subs({var: x}) for x in xs] plt.plot(xs, ys, 'ro') plt.savefig('sample2.svg') if __name__ == '__main__': f = input('Enter a function in one variable: ') var = input('Enter the variable t differentiate with respect to: ') var0 = float(input('Enter the initial value of the variable: ')) try: f = sympify(f) except SympifyError as err: print(f'Invalid function entered: {err}') else: var = symbols(var) d = Derivative(f, var).doit() var_min, xs = grad_descent(var0, d, var) print(f'{var.name}: {var_min}') print(f'Minimum value: {f.subs({var:var_min})}') draw(f, var, xs)
入出力結果(Terminal, Jupyter(IPython))
$ ./sample2.py Enter a function in one variable: 25 * 25 * sin(2 * theta) / 9.8 Enter the variable t differentiate with respect to: theta Enter the initial value of the variable: 0.001 theta: -0.785360851298204 Minimum value: -63.7755100265060 $
0 コメント:
コメントを投稿