module Nuggets::Array::RegressionMixin

Public Instance Methods

linear_least_squares → anArray click to toggle source

Calculates the linear least squares regression for the {x,y} pairs in array. If array only contains values instead of pairs, y will be the value and x will be each value's position (rank) in array.

# File lib/nuggets/array/regression_mixin.rb, line 38
def linear_least_squares
  return [] if empty?

  sx, sy, sq, sp, xys = 0.0, 0.0, 0.0, 0.0, first.respond_to?(:to_ary) ?
    self : self.class.new(size) { |i| [i + 1, at(i)] }

  xys.each { |x, y| sx += x; sy += y; sq += x ** 2; sp += x * y }

  b = (v = sq * size - sx ** 2) == 0 ? 0 : (sp * size - sx * sy) / v
  a = (sy - b * sx) / size

  xys.map { |x, _| [x, a + b * x] }
end
Also aliased as: llsq
linear_least_squares_incremental → anIncrementalLinearRegression click to toggle source

Returns an instance of IncrementalLinearRegression for array; array being a list of values (in contrast to linear_least_squares, which also accepts {x,y} pairs). Use IncrementalLinearRegression directly, or apply this method to an empty array, for more control over its input data.

# File lib/nuggets/array/regression_mixin.rb, line 62
def linear_least_squares_incremental
  IncrementalLinearRegression.new(*self)
end
Also aliased as: llsqi
llsq()