#format python """SimpleRegressionAnalysis """ import unittest, math class SimpleRegressionAnalyzer: """when y = a + b x, and inputdata is [(x1,y1),(x2,y2)...] """ def __init__(self): self.r = self.a = self.b = None def setData(self, anTwoTuplesList): self.data = anTwoTuplesList self._regress() def _avg(self): sumX = sumY = 0 n = float(len(self.data)) for eachX, eachY in self.data: sumX+=eachX sumY+=eachY return (sumX/n, sumY/n) def _regress(self): s_xy = 0; s_xx = 0; s_yy = 0 avgX, avgY = self._avg() for eachX, eachY in self.data: xd=eachX-avgX yd=eachY-avgY s_xy += xd*yd s_xx += xd**2 s_yy += yd**2 self.b = s_xy / s_xx self.a = avgY - self.b * avgX try: self.r = s_xy / (math.sqrt(s_xx * s_yy)) except ZeroDivisionError: self.r = 0 def getConstants(self): return (self.a, self.b) def getCoefficient(self): return self.r def setConstants(self, a, b): self.a = a self.b = b def setCoefficient(self, r): self.r = r def getValue(self, x): return self.a + self.b * x class RegressionTest(unittest.TestCase): def setUp(self): inputData = [(1.0, 1.0), (3.0, 4.0)] self.sra = SimpleRegressionAnalyzer(inputData) def testAverage(self): self.assertEquals((2.0,2.5), self.sra._avg()) def testGetConstants(self): self.assertEquals((-0.5,1.5), self.sra.getConstants()) def testGetCoefficient(self): self.assertEquals(1, self.sra.getCoefficient()) def testZeroDivision(self): self.sra.setData([(1.0,1.0),(2.0,1.0)]) self.assertEquals(0, self.sra.getCoefficient()) if __name__=='__main__': unittest.main(argv=('','-v'))