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)


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

#offsetObject

Returns the value of attribute offset.



182
183
184
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 182

def offset
  @offset
end

#slopeObject

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

#axisObject



207
208
209
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 207

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

#fitObject



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