Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to calculate a simple linear regression line.(Ver.2)
#! /usr/local/bin/ruby
#*********************************************
# Ruby script to calculate a simple lenear regression line.
# : y = a + b * x
# : 連立方程式を ガウスの消去法で解く方法
#*********************************************
#
class Array
def reg_line(y)
# 以下の場合は例外スロー
# - 引数の配列が Array クラスでない
# - 自身配列が空
# - 配列サイズが異なれば例外
raise "Argument is not a Array class!" unless y.class == Array
raise "Self array is nil!" if self.size == 0
raise "Argument array size is invalid!" unless self.size == y.size
sum_x = self.inject(0) { |s, a| s += a }
sum_y = y.inject(0) { |s, a| s += a }
sum_xx = self.inject(0) { |s, a| s += a * a }
sum_xy = self.zip(y).inject(0) { |s, a| s += a[0] * a[1] }
mtx = [
[self.size, sum_x, sum_y],
[ sum_x, sum_xx, sum_xy]
]
ans = solve_ge(mtx)
{intercept: ans[0][-1], slope: ans[1][-1]}
end
private
# 連立方程式の解(ガウスの消去法)
def solve_ge(a)
n = a.size
# 前進消去
(n - 1).times do |k|
(k + 1).upto(n - 1) do |i|
d = a[i][k] / a[k][k].to_f
(k + 1).upto(n) do |j|
a[i][j] -= a[k][j] * d
end
end
end
# 後退代入
(n - 1).downto(0) do |i|
d = a[i][n]
(i + 1).upto(n - 1) do |j|
d -= a[i][j] * a[j][n]
end
a[i][n] = d / a[i][i].to_f
end
return a
end
end
# 説明変数と目的変数
ary_x = [107, 336, 233, 82, 61, 378, 129, 313, 142, 428]
ary_y = [286, 851, 589, 389, 158, 1037, 463, 563, 372, 1020]
puts "説明変数 X = {#{ary_x.join(', ')}}"
puts "目的変数 Y = {#{ary_y.join(', ')}}"
puts "---"
# 単回帰直線算出(切片と傾き)
reg_line = ary_x.reg_line(ary_y)
puts "切片 a = #{reg_line[:intercept]}"
puts "傾き b = #{reg_line[:slope]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.