rubyで線形関数の最小二乗法(linear least squares)の関数を、[Ruby] 最小二乗法で配列内の値の傾きを得る関数と今日の最小二乗法を参考に書いてみた。というより、むしろ、今日の最小二乗法にrubyだと難しいみたいなことが書いてあったので書いてみた。
def linear_least_squares(list) b = c = d = e = 0.0 list.each do |(x,y)| b += x**2 c += y d += x*y e += x end n = list.size return [(n*d-c*e)/(n*b-e**2), (b*c-d*e)/(n*b-e**2)] end # 以下はtest code 10.times do xy_list = [] (1..100).each do |x| xy_list << [x + rand-0.5, x+3 +rand-0.5] end puts linear_least_squares(xy_list).join("\t") end特に複雑なことはない。上記のテストコードの実行結果。
0.997689631853556 3.14496678815436 1.00028891230551 3.02622786430138 1.00066550054929 2.95155544278623 0.999653790020994 3.04778392777951 0.999075573909202 3.01499083993695 0.999654091040374 3.05364819512169 1.00138145731397 3.02799150236269 0.999100753739204 2.9783070845857 1.00138033542006 2.95908331109936 0.998072938174775 3.03631384409164本当はxにランダムを加えるのは違うのだが。