Created
June 7, 2017 01:37
-
-
Save StaverDmitry/e0d6bad9ed83b5587af87ec81b7ac521 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LinearRegression | |
def initialize(hash) | |
x = hash.keys | |
y = hash.values | |
@xs, @ys = x, y | |
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 = (0...@xs.length).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