Module: Nuggets::Array::RegressionMixin
- Included in:
- Array
- Defined in:
- lib/nuggets/array/regression_mixin.rb
Defined Under Namespace
Classes: IncrementalLinearRegression
Instance Method Summary collapse
-
#linear_least_squares ⇒ Object
(also: #llsq)
call-seq: array.linear_least_squares => anArray.
-
#linear_least_squares_incremental ⇒ Object
(also: #llsqi)
call-seq: array.linear_least_squares_incremental => anIncrementalLinearRegression.
Instance Method Details
#linear_least_squares ⇒ Object Also known as: llsq
call-seq:
array.linear_least_squares => anArray
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.
38 39 40 41 42 43 44 45 46 47 48 49 50 |
# 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 |
#linear_least_squares_incremental ⇒ Object Also known as: llsqi
call-seq:
array.linear_least_squares_incremental => anIncrementalLinearRegression
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.
62 63 64 |
# File 'lib/nuggets/array/regression_mixin.rb', line 62 def linear_least_squares_incremental IncrementalLinearRegression.new(*self) end |