Skip to content

Instantly share code, notes, and snippets.

@corroded
Created November 28, 2011 02:53
Show Gist options
  • Save corroded/1398888 to your computer and use it in GitHub Desktop.
Save corroded/1398888 to your computer and use it in GitHub Desktop.
w1 and w0 solver for linear regression in ai class
M = 5
XS = [1,3,4,5,9]
YS = [2,5.2,6.8,8.4,14.8]
#XS = [0,1,2,3,4]
#YS = [3,6,7,8,11]
def calc_w1
((M * summation_of_x_and_y) - (summation_of_x * summation_of_y)) / ((M * summation_of_x_squared) - (summation_of_x * summation_of_x))
end
def calc_w0
(summation_of_y / M) - ((calc_w1 / M) * summation_of_x)
end
def summation_of_x_and_y
summation = []
(0..4).each do |i|
summation << XS[i] * YS[i]
end
summation.reduce(:+).to_f
end
def summation_of_x
XS.reduce(:+).to_f
end
def summation_of_y
YS.reduce(:+).to_f
end
def summation_of_x_squared
total = 0
XS.map do |x|
total = total + x*x
end
total.to_f
end
puts calc_w1
puts calc_w0
puts (summation_of_y / M) - ((calc_w1 / M) * summation_of_x)
puts summation_of_y
puts summation_of_x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment