Class: ComplexityAssert::SimpleLinearRegression
- Inherits:
-
Object
- Object
- ComplexityAssert::SimpleLinearRegression
- Defined in:
- lib/complexity_assert/simple_linear_regression.rb
Overview
Performs basic linear regression on a set of points
Instance Method Summary collapse
-
#initialize(xs, ys) ⇒ SimpleLinearRegression
constructor
A new instance of SimpleLinearRegression.
- #mean(values) ⇒ Object
- #slope ⇒ Object
-
#y_intercept ⇒ Object
TODO cache all these instead of computing it every time.
Constructor Details
#initialize(xs, ys) ⇒ SimpleLinearRegression
Returns a new instance of SimpleLinearRegression.
6 7 8 9 10 11 |
# File 'lib/complexity_assert/simple_linear_regression.rb', line 6 def initialize(xs, ys) @xs, @ys = xs, ys if @xs.length != @ys.length raise "Unbalanced data. xs need to be same length as ys" end end |
Instance Method Details
#mean(values) ⇒ Object
34 35 36 37 |
# File 'lib/complexity_assert/simple_linear_regression.rb', line 34 def mean(values) total = values.reduce(0) { |sum, x| x + sum } Float(total) / Float(values.length) end |
#slope ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/complexity_assert/simple_linear_regression.rb', line 19 def slope x_mean = mean(@xs) y_mean = mean(@ys) numerator = (0...@xs.length).reduce(0) do |sum, i| sum + ((@xs[i] - x_mean) * (@ys[i] - y_mean)) end denominator = @xs.reduce(0) do |sum, x| sum + ((x - x_mean) ** 2) end (numerator / denominator) end |
#y_intercept ⇒ Object
TODO cache all these instead of computing it every time
15 16 17 |
# File 'lib/complexity_assert/simple_linear_regression.rb', line 15 def y_intercept mean(@ys) - (slope * mean(@xs)) end |