Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active December 24, 2018 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/dd94e2c3394084580333 to your computer and use it in GitHub Desktop.
Save komasaru/dd94e2c3394084580333 to your computer and use it in GitHub Desktop.
Ruby script to calculate a simple linear regression line.
#*********************************************
# Ruby script to calculate a simple linear regression line.
#*********************************************
#
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
# x の総和
sum_x = self.inject(0) { |s, a| s += a }
# y の総和
sum_y = y.inject(0) { |s, a| s += a }
# x^2 の総和
sum_xx = self.inject(0) { |s, a| s += a * a }
# x * y の総和
sum_xy = self.zip(y).inject(0) { |s, a| s += a[0] * a[1] }
# 切片 a
a = sum_xx * sum_y - sum_xy * sum_x
a /= (self.size * sum_xx - sum_x * sum_x).to_f
# 傾き b
b = self.size * sum_xy - sum_x * sum_y
b /= (self.size * sum_xx - sum_x * sum_x).to_f
{intercept: a, slope: b}
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