class Nuggets::Array::RegressionMixin::IncrementalLinearRegression
Inspired by Incremental Simple Linear Regression in Ruby.
Use push
to add a single {x,y}
pair, add
to add a list of y
values, and <<
to add a single y
value. Whenever a single y
value is added, it's associated with an x
value of its position (rank) in the data series.
Call to_a
(or any Enumerable
method) to work with the regression points.
Public Class Methods
new(*ys)
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 80 def initialize(*ys) 81 clear 82 add(*ys) 83 end
Public Instance Methods
<<(y)
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 107 def <<(y) 108 push(@cnt + 1, y) 109 end
add(*ys)
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 102 def add(*ys) 103 ys.each { |y| self << y } 104 self 105 end
at(x)
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 119 def at(x) 120 @y + slope * (x - @x) 121 end
Also aliased as: []
clear()
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 85 def clear 86 @x = @y = @xx = @xy = 0.0 87 @cnt, @slope = 0, nil 88 self 89 end
each() { |x = i + 1, at(x)| ... }
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 125 def each 126 @cnt.times { |i| yield [x = i + 1, at(x)] } 127 self 128 end
intercept()
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 115 def intercept 116 at(0) 117 end
push(x, y)
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 91 def push(x, y) 92 cnt, @slope = @cnt += 1, nil 93 94 @x += (x - @x) / cnt 95 @y += (y - @y) / cnt 96 @xx += (x * x - @xx) / cnt 97 @xy += (x * y - @xy) / cnt 98 99 self 100 end
slope()
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 111 def slope 112 @slope ||= @cnt < 2 ? 0 : (@xy - @x * @y) / (@xx - @x * @x) 113 end
to_a(range = nil)
click to toggle source
Calls superclass method
# File lib/nuggets/array/regression_mixin.rb 130 def to_a(range = nil) 131 range ? range.map { |x| [x, at(x)] } : super() 132 end
to_s()
click to toggle source
# File lib/nuggets/array/regression_mixin.rb 134 def to_s 135 s, i = slope, intercept 136 137 y = s == 0 ? i : begin 138 x = s.abs == 1 ? "#{'-' if s < 0}x" : "#{s} * x" 139 i == 0 ? x : "#{x} #{i < 0 ? '-' : '+'} #{i.abs}" 140 end 141 142 "y := #{y}".gsub(/\.0\b/, '') 143 end