回帰学習を簡単に実装してみた

Python3.5で教師あり学習の回帰の簡単な実装。

sinカーブを学習してみた。 パラメータの個数は1,3,5,7。

# coding: utf-8
import scipy as sp
import matplotlib.pyplot as plt

# 次元ごとに取得
x = sp.arange(0, 10, 0.1)
y = [ sp.sin(i) for i in x]
# NaNの除去
# x = x[~sp.isnan(y)] 
# y = y[~sp.isnan(y)]
# グラフに散布
plt.scatter(x,y)

# 学習(回帰)
fx = sp.linspace(0, x[-1], 1000)
f1 = sp.poly1d(sp.polyfit(x, y, 1))
f3 = sp.poly1d(sp.polyfit(x, y, 3))
f5 = sp.poly1d(sp.polyfit(x, y, 5))
f7 = sp.poly1d(sp.polyfit(x, y, 7))
# 描画
plt.plot(fx, f1(fx), c="red", linewidth=2)
plt.plot(fx, f3(fx), c="green", linewidth=2)
plt.plot(fx, f5(fx), c="blue", linewidth=2)
plt.plot(fx, f7(fx), c="pink", linewidth=2)

# グラフの設定と表示
plt.title("Title")
plt.xlabel("x label")
plt.ylabel("y label")
plt.xticks([w*7*24 for w in range(10)],
    ['week %i'%w for w in range(10)])
plt.legend(["d=%i" % f1.order, "d=%i" % f3.order, "d=%i" % f5.order, "d=%i" % f7.order], loc="upper left")
plt.autoscale(tight=True)
plt.grid()
plt.show()

こんな感じのグラフが出たらOK。

f:id:carumisu:20160516100015p:plain