class Callidus::LinearRegression

Attributes

correlation[R]
input[RW]
output[RW]
predicted_output[RW]
slope[R]
standard_error[R]
y_intercept[R]

Public Class Methods

new(ip = [], op = []) click to toggle source
# File lib/src/LinearRegression.rb, line 15
def initialize(ip = [], op = [])
    @input = ip
    @output = op

    @trained = false
end

Public Instance Methods

find_correlation() click to toggle source
# File lib/src/LinearRegression.rb, line 64
def find_correlation
    assert_trained()

    mean = @output.sum/@output.size

    diffYM = @output.map { |y| (y - mean) ** 2 };
    diffPYM = @predicted_output.map { |y| (y - mean) ** 2 };

    @correlation = (diffPYM.sum/diffYM.sum).round(3)

    self
end
find_standard_error() click to toggle source
# File lib/src/LinearRegression.rb, line 77
def find_standard_error
    assert_trained()

    n = @input.size > @output.size ? @output.size : @input.size

    diffs = []

    n.times do |i|
        diffs << (@predicted_output[i] - @output[i]) ** 2
    end

    @standard_error = (Math.sqrt(diffs.sum/(n - 2.0))).round(3)

    self
end
formatted() click to toggle source
# File lib/src/LinearRegression.rb, line 28
def formatted
    assert_trained()

    "f(x) = #{@slope}x + #{@y_intercept}"
end
predict(x) click to toggle source
# File lib/src/LinearRegression.rb, line 93
def predict(x)
    assert_trained()
    
    x * @slope + @y_intercept
end
train() click to toggle source
# File lib/src/LinearRegression.rb, line 34
def train
    sum_x = 0
    sum_y = 0
    sum_xy = 0
    sum_xx = 0

    n = @input.size > @output.size ? @output.size : @input.size

    @predicted_output = []

    n.times do |i|
        x = @input[i]
        y = @output[i]

        sum_x += x
        sum_y += y
        sum_xx += (x * x)
        sum_xy += (x * y)
    end

    @slope = ((n * sum_xy - sum_x * sum_y).to_f / (n * sum_xx - sum_x * sum_x).to_f).round(3)
    @y_intercept = ((sum_y / n).to_f - (@slope * sum_x).to_f / n.to_f).round(3)

    @predicted_output = @input.map { |x| (x * @slope + @y_intercept).round(3) }

    @trained = true

    self.find_correlation.find_standard_error
end

Private Instance Methods

assert_trained(method = "train") click to toggle source
# File lib/src/LinearRegression.rb, line 22
        def assert_trained(method = "train")
    if !@trained
        raise Util::UntrainedError.new("LinearRegression")
    end
end