Created
September 30, 2013 10:37
-
-
Save anonymous/6762027 to your computer and use it in GitHub Desktop.
Univariate modeler of a series of numbers. The numbers are regarded be sample from 1, 2, 3, 4
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
from scipy.linalg import pinv | |
from numpy import abs, arange, ones, dot, finfo, mat, vstack | |
from sympy import Lambda, var | |
from numpy.testing import assert_allclose | |
class UniModeler(): | |
def __init__(self, data=None): | |
self.data = data | |
self._model = lambda x: 0 | |
def set_data(self, data): | |
self.data = data | |
self._model = lambda x: 0 | |
def get_data(self): | |
return self.data | |
def estimate_linear(self): | |
"""y = X*b; b = pinv(X)*y""" | |
N = len(self.data) | |
design_matrix = vstack((ones(N), arange(1,N+1))).T | |
b = dot(pinv(design_matrix), mat(self.data).T) | |
x = var('x') | |
self._model = Lambda(x, b[1]*x+b[0]) | |
def estimate(self): | |
if self._model is None: | |
return None | |
return self.estimate_linear() | |
def predict(self, x): | |
return self._model(x) | |
def predict_many(self, xs): | |
return [ self.predict(x) for x in xs ] | |
def test_set_data(): | |
um = UniModeler() | |
um.set_data([1, 2, 3]) | |
assert [1, 2, 3] == um.get_data() | |
um.set_data([1]) | |
assert [1] == um.get_data() | |
def test_predict(): | |
um = UniModeler() | |
um.set_data([1, 2, 3]) | |
um.estimate() | |
small = 100 * finfo('double').eps | |
assert abs(0 - um.predict(0)) < small | |
assert abs(1 - um.predict(1)) < small | |
assert abs(1 - um.predict_many([0, 1])[1]) < small | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment