Class: Array::LinearRegression
- Inherits:
-
Object
- Object
- Array::LinearRegression
- Defined in:
- lib/ar_result_calculations/ar_result_calculations.rb
Overview
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 ⇒ 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.
151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 151 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
#offset ⇒ Object
Returns the value of attribute offset.
149 150 151 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 149 def offset @offset end |
#slope ⇒ Object
Returns the value of attribute slope.
149 150 151 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 149 def slope @slope end |
Instance Method Details
#axis ⇒ Object
174 175 176 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 174 def axis (0...@size).to_a end |
#fit ⇒ Object
166 167 168 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 166 def fit return axis.map{|data| predict(data) } end |
#predict(x) ⇒ Object
170 171 172 |
# File 'lib/ar_result_calculations/ar_result_calculations.rb', line 170 def predict( x ) y = @slope * x + @offset end |