Class: Array::LinearRegression

Inherits:
Object
  • Object
show all
Defined in:
lib/ar_result_calculations/ar_result_calculations.rb

Overview

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dx, dy = nil) ⇒ LinearRegression

Returns a new instance of LinearRegression.

Raises:

  • (ArgumentError)


151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 151

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

#offsetObject

Returns the value of attribute offset.



149
150
151
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 149

def offset
  @offset
end

#slopeObject

Returns the value of attribute slope.



149
150
151
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 149

def slope
  @slope
end

Instance Method Details

#axisObject



174
175
176
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 174

def axis
  (0...@size).to_a
end

#fitObject



166
167
168
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 166

def fit
  return axis.map{|data| predict(data) }
end

#predict(x) ⇒ Object



170
171
172
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 170

def predict( x )
  y = @slope * x + @offset
end