最急降下法による回帰分析

参考

Pythonで最急勾配法を実装し、グラフを描く - minus9d's diary

 

本編

Lecture 2 | Machine Learning (Stanford) - YouTube

の最初の回帰分析を実装

 

import numpy as np
import matplotlib.pyplot as plt

# 学習データ
m = np.array([[2104, 400],
              [1600, 330],
              [2400, 369],
              [1416, 232],
              [3000, 540]])
# 使いにくいので、予め分けておく
x = m[:, 0]
y = m[:, 1]
# 繰り返し回数
r = 10
# 変数
theta = np.array([0.0, 0.0])
# 最適化の係数
alpha = 0.0000001

for i in range(r):
    #print([(h(x[k], theta) - y[k])*x[k] for k in range(len(x))])
    # それぞれの偏微分の計算
    J0 = np.mean((theta[0] + theta[1]*x - y))
    J1 = np.mean((theta[0] + theta[1]*x - y) * x)
    # 値の更新
    theta[0] -= alpha * J0
    theta[1] -= alpha * J1
  
    print(theta)

# 学習データのプロット
plt.plot(x, y, '*')
xm = np.array(range(0, 3500, 1))
ym = theta[0] + xm * theta[1]
plt.plot(xm, ym)
plt.xlim(0, 3500)
plt.show()

#def h(x, theta):
#    return theta[0] + theta[1]*x

 f:id:shiriases:20170503013303p:plain

実際に実装してみると勉強になるけど時間がかかる...