Skip to content

Instantly share code, notes, and snippets.

# komasaru/regression_curve_exp.rb Created May 6, 2019

Ruby script to calculate a simple regression curve.(exp)
 #! /usr/local/bin/ruby #********************************************* # Ruby script to calculate a simple regression curve. # : y = a * b**x # : 連立方程式を ガウスの消去法で解く方法 #********************************************* # class Array def reg_curve_exp(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_x2 = self.inject(0) { |s, a| s += a * a } sum_ly = y.inject(0) { |s, a| s += Math.log(a) } sum_xly = self.zip(y).inject(0) { |s, a| s += a[0] * Math.log(a[1]) } mtx = [ [self.size, sum_x, sum_ly], [ sum_x, sum_x2, sum_xly] ] ans = solve_ge(mtx) {a: Math.exp(ans[0][-1]), b: Math.exp(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] ary_x = [83, 71, 64, 69, 69, 64, 68, 59, 81, 91, 57, 65, 58, 62] ary_y = [183, 168, 171, 178, 176, 172, 165, 158, 183, 182, 163, 175, 164, 175] puts "説明変数 X = {#{ary_x.join(', ')}}" puts "目的変数 Y = {#{ary_y.join(', ')}}" puts "---" # 単回帰曲線算出 reg_line = ary_x.reg_curve_exp(ary_y) puts "a = #{reg_line[:a]}" puts "b = #{reg_line[:b]}"
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.