Class: LinearRegression
- Inherits:
-
Object
- Object
- LinearRegression
- Defined in:
- lib/regression.rb
Instance Attribute Summary collapse
-
#offset ⇒ Object
Returns the value of attribute offset.
-
#slope ⇒ Object
Returns the value of attribute slope.
Instance Method Summary collapse
- #axis ⇒ Object
- #fit(dx = nil) ⇒ Object
-
#initialize(dx, dy = nil) ⇒ LinearRegression
constructor
A new instance of LinearRegression.
- #predict(x) ⇒ Object
Constructor Details
#initialize(dx, dy = nil) ⇒ LinearRegression
Returns a new instance of LinearRegression.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/regression.rb', line 5 def initialize (dx, dy=nil) @size = dx.size dy,dx = dx,axis() unless dy # make 2D if given 1D raise "arguments 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 ) @offset = (sy - @slope*sx) / @size end |
Instance Attribute Details
#offset ⇒ Object
Returns the value of attribute offset.
3 4 5 |
# File 'lib/regression.rb', line 3 def offset @offset end |
#slope ⇒ Object
Returns the value of attribute slope.
3 4 5 |
# File 'lib/regression.rb', line 3 def slope @slope end |
Instance Method Details
#axis ⇒ Object
29 30 31 |
# File 'lib/regression.rb', line 29 def axis (0...@size).to_a end |
#fit(dx = nil) ⇒ Object
20 21 22 23 |
# File 'lib/regression.rb', line 20 def fit(dx = nil) dx = axis unless dx return dx.map{|data| predict(data) } end |
#predict(x) ⇒ Object
25 26 27 |
# File 'lib/regression.rb', line 25 def predict( x ) y = @slope * x + @offset end |