Class: Array::LinearRegression
- Inherits:
-
Object
- Object
- Array::LinearRegression
- Defined in:
- lib/ar_result_calculations/ar_result_calculations.rb
Overview
Instance Attribute Summary collapse
-
#offset ⇒ Object
Returns the value of attribute offset.
-
#slope ⇒ Object
Returns the value of attribute slope.
Instance Method Summary collapse
- #axis ⇒ Object
- #fit ⇒ Object
-
#initialize(dx, dy = nil) ⇒ LinearRegression
constructor
A new instance of LinearRegression.
- #predict(x) ⇒ Object
Constructor Details
#initialize(dx, dy = nil) ⇒ LinearRegression
Returns a new instance of LinearRegression.
184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 184 def initialize dx, dy=nil @size = dx.size dy,dx = dx,axis() unless dy # make 2D if given 1D raise ArgumentError, "[regression] Arguments are not same length!" unless @size == dy.size sxx = sxy = sx = sy = 0 dx.zip(dy).each do |x,y| sxy += x*y sxx += x*x sx += x sy += y end @slope = ( @size * sxy - sx * sy ) / ( @size * sxx - sx * sx ) rescue 0 @offset = (sy - @slope * sx) / @size end |
Instance Attribute Details
#offset ⇒ Object
Returns the value of attribute offset.
182 183 184 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 182 def offset @offset end |
#slope ⇒ Object
Returns the value of attribute slope.
182 183 184 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 182 def slope @slope end |
Instance Method Details
#axis ⇒ Object
207 208 209 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 207 def axis (0...@size).to_a end |
#fit ⇒ Object
199 200 201 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 199 def fit return axis.map{|data| predict(data) } end |
#predict(x) ⇒ Object
203 204 205 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 203 def predict( x ) y = @slope * x + @offset end |