Skip to content

Instantly share code, notes, and snippets.

@charly
Forked from Serabe/gist:990667
Last active January 1, 2016 07:49
Show Gist options
  • Save charly/8114471 to your computer and use it in GitHub Desktop.
Save charly/8114471 to your computer and use it in GitHub Desktop.
require 'matrix'
def regression x, y, degree
x_data = x.map {|xi| (0..degree).map{|pow| (xi**pow) }}
mx = Matrix[*x_data]
my = Matrix.column_vector y
((mx.t * mx).inv * mx.t * my).transpose.to_a[0].reverse
end
# SAME AS ...
class SimpleLinearRegression
def initialize(xs, ys)
@xs, @ys = xs, ys
if @xs.length != @ys.length
raise "Unbalanced data. xs need to be same length as ys"
end
end
def y_intercept
mean(@ys) - (slope * mean(@xs))
end
def slope
x_mean = mean(@xs)
y_mean = mean(@ys)
numerator = ([email protected]).reduce(0) do |sum, i|
sum + ((@xs[i] - x_mean) * (@ys[i] - y_mean))
end
denominator = @xs.reduce(0) do |sum, x|
sum + ((x - x_mean) ** 2)
end
(numerator / denominator)
end
def mean(values)
total = values.reduce(0) { |sum, x| x + sum }
Float(total) / Float(values.length)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment