Juliaの練習がてら簡単な線形回帰を行った。
以下のことが分かる練習にはちょうど良いシンプルなコードだ。
- 乱数をどう発生させるか
- 計画行列をどう作るか
- Gadflyを使って2つのプロットを重ねるにはどうするか
- Gadflyを使って軸の設定をどうするか
これらがわかれば自作する当面の計算にはこまらない気がする…
linreg()はバイアス項を勝手に計算してくれるみたいなので、入れなくてよいみたいだ。
# #Regression Example
using Gadfly
using Distributions
N = 15
xdata = (rand(N) - 0.5) * 2 * pi
σ² = 0.5
function noisy(x, r=rand(Normal(0, σ²))
return sin(x) + r
end
#X results in Nx9 array
t = noisy(xdata);
X = Float64[x^i for x=xdata, i=[1:9]] #bias is not needed for linreg(). it will interpolate automatically
#regression by linreg
coeffs = linreg(X, t)
#plotting
f = x -> coeffs[1] + sum([coeffs[i]*x^(i-1) for i = [2:10]])
x_reg = linspace(-pi, pi, 100)
y_reg = [f(xi) for xi=x_reg]
plot(layer(x=x_reg, y=y_reg, Geom.line), layer(x=xdata, y=t, Geom.point),
Coord.Cartesian(xmin=-pi, xmax=pi, ymin=-1.5, ymax=1.5))