Created
March 6, 2012 12:15
-
-
Save judy2k/1985914 to your computer and use it in GitHub Desktop.
Predict a value using least squares method.
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
import numpy as np | |
def get_line(points): | |
x = np.array([p[0] for p in points]) | |
y = np.array([p[1] for p in points]) | |
A = np.vstack([x, np.ones(len(x))]).T | |
m, c = np.linalg.lstsq(A, y)[0] | |
return m, c | |
def get_y(x, m, c): | |
return m * x + c |
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
import unittest | |
class Tests(unittest.TestCase): | |
@property | |
def ls(self): | |
import leastsquares | |
return leastsquares | |
def test_ls(self): | |
m, c = self.ls.get_line([(0,0), (1,1), (2,2), (3,3)]) | |
self.assertAlmostEqual(m, 1.0) | |
self.assertAlmostEqual(c, 0.0) | |
self.assertAlmostEqual(m * 4.0 + c, 4.0) | |
m, c = self.ls.get_line([(0,1), (1,2), (2,3), (3,4)]) | |
self.assertAlmostEqual(m, 1.0) | |
self.assertAlmostEqual(c, 1.0) | |
self.assertAlmostEqual(m * 4.0 + c, 5.0) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment