Skip to content

Instantly share code, notes, and snippets.

@oem
Last active April 16, 2018 11:00
Show Gist options
  • Save oem/ddff9542fc09b3df110f8ac02441a828 to your computer and use it in GitHub Desktop.
Save oem/ddff9542fc09b3df110f8ac02441a828 to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
require 'matrix'
module LinearRegression
def predict(features, theta)
features * theta
end
def cost_function(features, labels, theta)
m = features.row_count
predictions = predict(features, theta)
squared_errors = (predictions - labels).map { |error| error**2 }
(1.0 / (2.0 * m)) * squared_errors.reduce { |a, b| a + b }
end
def normal_equation(features, labels)
(features.transpose * features).inverse * features.transpose * labels
end
end
class TestLinearRegression < MiniTest::Test
include LinearRegression
def setup
@features = Matrix[[10, 1000, 10], [5, 800, 2], [12, 2500, 3]]
@labels = Vector[900, 600, 1800]
@initial_theta = Vector[200, -0.1, -10]
end
def test_predict_with_inital_theta
assert_equal Vector[1800, 900, 2120], predict(@features, @initial_theta)
end
def test_cost_with_initial_theta
assert_equal 167_066.67, cost_function(@features, @labels, @initial_theta).round(2)
end
def test_normal_equation
assert_equal Vector[5.0, 0.675, 17.5], normal_equation(@features, @labels)
end
def test_cost_function_with_optimal_theta
optimal_theta = Vector[5.0, 0.675, 17.5]
assert_equal 0, cost_function(@features, @labels, optimal_theta)
end
def test_predict_with_optimal_theta
optimal_theta = normal_equation(@features, @labels)
assert_equal Vector[900, 600, 1800], predict(@features, optimal_theta)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment