Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Created December 30, 2012 13:13
Show Gist options
  • Save vderyagin/4412781 to your computer and use it in GitHub Desktop.
Save vderyagin/4412781 to your computer and use it in GitHub Desktop.
half-ass implementation of linear regression in Ruby
#! /usr/bin/env ruby
class LinearRegression
attr_reader :coords, :size
def initialize(coords)
@coords = coords
@size = coords.size
end
def xs
coords.map(&:first)
end
def ys
coords.map(&:last)
end
def mean_x
@mean_x ||= xs.inject(:+) / size
end
def mean_y
@mean_y ||= ys.inject(:+) / size
end
def a
mean_y - b * mean_x
end
def b
num = 0.0
denom = 0.0
coords.each do |x, y|
num += (x - mean_x) * (y - mean_y)
denom += (x - mean_x) ** 2
end
num / denom
end
def r
num = 0.0
denom1 = 0.0
denom2 = 0.0
coords.each do |x, y|
num += (x - mean_x) * (y - mean_y)
denom1 += (x - mean_x) ** 2
denom2 += (y - mean_y) ** 2
end
num / (denom1 * denom2) ** 0.5
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment