Class: MoreMath::LinearRegression
- Defined in:
- lib/more_math/linear_regression.rb
Overview
This class computes a linear regression for the given image and domain data sets.
Instance Attribute Summary collapse
-
#a ⇒ Object
readonly
The slope of the line.
-
#b ⇒ Object
readonly
The offset of the line.
-
#domain ⇒ Object
readonly
The domain data as an array.
-
#image ⇒ Object
readonly
The image data as an array.
Instance Method Summary collapse
-
#initialize(image, domain = (0...image.size).to_a) ⇒ LinearRegression
constructor
A new instance of LinearRegression.
- #r2 ⇒ Object
-
#residuals ⇒ Object
Returns the residuals of this linear regression in relation to the given domain and image.
-
#slope_zero?(alpha = 0.05) ⇒ Boolean
Return true if the slope of the underlying data (not the sample data passed into the constructor of this LinearRegression instance) is likely (with alpha level alpha) to be zero.
Constructor Details
#initialize(image, domain = (0...image.size).to_a) ⇒ LinearRegression
Returns a new instance of LinearRegression.
5 6 7 8 9 10 |
# File 'lib/more_math/linear_regression.rb', line 5 def initialize(image, domain = (0...image.size).to_a) image.size != domain.size and raise ArgumentError, "image and domain have unequal sizes" @image, @domain = image, domain compute end |
Instance Attribute Details
#a ⇒ Object (readonly)
The slope of the line.
19 20 21 |
# File 'lib/more_math/linear_regression.rb', line 19 def a @a end |
#b ⇒ Object (readonly)
The offset of the line.
22 23 24 |
# File 'lib/more_math/linear_regression.rb', line 22 def b @b end |
#domain ⇒ Object (readonly)
The domain data as an array.
16 17 18 |
# File 'lib/more_math/linear_regression.rb', line 16 def domain @domain end |
#image ⇒ Object (readonly)
The image data as an array.
13 14 15 |
# File 'lib/more_math/linear_regression.rb', line 13 def image @image end |
Instance Method Details
#r2 ⇒ Object
45 46 47 48 49 50 51 52 |
# File 'lib/more_math/linear_regression.rb', line 45 def r2 image_seq = MoreMath::Sequence.new(@image) sum_res = residuals.inject(0.0) { |s, r| s + r ** 2 } [ 1.0 - sum_res / image_seq.sum_of_squares, 0.0, ].max end |
#residuals ⇒ Object
Returns the residuals of this linear regression in relation to the given domain and image.
37 38 39 40 41 42 43 |
# File 'lib/more_math/linear_regression.rb', line 37 def residuals result = [] @domain.zip(@image) do |x, y| result << y - (@a * x + @b) end result end |
#slope_zero?(alpha = 0.05) ⇒ Boolean
Return true if the slope of the underlying data (not the sample data passed into the constructor of this LinearRegression instance) is likely (with alpha level alpha) to be zero.
27 28 29 30 31 32 33 |
# File 'lib/more_math/linear_regression.rb', line 27 def slope_zero?(alpha = 0.05) df = @image.size - 2 return true if df <= 0 # not enough values to check t = tvalue(alpha) td = TDistribution.new df t.abs <= td.inverse_probability(1 - alpha.abs / 2.0).abs end |