LoginSignup
0
0

More than 3 years have passed since last update.

勾配降下法をアニメーション化した

Last updated at Posted at 2019-06-30

機械学習でよく使われる勾配降下法をアニメーション化した。
勾配降下法を使うとパラメータの値を逐次的に更新していくことによって一番尤もらしいパラメータの値を求められる。
関数$f(\theta)$のパラメータ$\theta$のj回目の更新式は以下のように表せる。

\theta_j := \theta_j - \eta f'(\theta)

毎更新のたびに、$\theta$から$f'(\theta)$と学習率$\eta$の積を引いていく。値が収束するまでこれを続ける。


%matplotlib nbagg
fig = plt.figure()
x = np.linspace(-10, 10)
y = x ** 2
plt.ylim(-10, 100)
plt.plot(x, y)
ims = []
lr = 0.1
p = 9
count = 0
while True:
    count += 1
    q = p ** 2
    slope = 2 * p
    intercept = q - (abs(p) * slope)
    y2 = intercept + x * slope
    img = plt.plot(x, y2)
    ims.append(img)
    diff = slope * 2 * lr # 傾き * 学習率がdiff
    p = p - diff
    if abs(slope) < 0.1:
        break



ani = animation.ArtistAnimation(fig, ims, interval=300)
plt.show()

anim-compressor.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0