points = list(enumerate([1,3,2.5,6,5,5.2,8,6.3,6.1,5.8,5.5,5.7,5.8,2.9,1.2])) # for x,y in points: print x, y def splits(points, f=list): return [(x - 0.5, f(points[x-2:x+1])) for x in range(2, len(points))] def piecewise(points, f): results = splits(points, f) return ':'.join(('x<%.1f?%s' % (x,y)) for x,y in results) + (':%s' % results[-1][1]) def meanY(points): return sum(y for x,y in points)/len(points) def regression(points): n = len(points) w1 = ((n*sum(x*y for x,y in points) - sum(x for x,y in points)*sum(y for x,y in points)) / (n*sum(x**2 for x,y in points)-sum(x for x,y in points)**2)) w0 = (sum(y for x,y in points) - w1*sum(x for x,y in points)) / n return '%.2f*x + %.2f' % (w1, w0) def lwr(points): return 'W(x, %s)' % ','.join('%.1f,%.1f' % (x,y) for (x,y) in points) def NNavg(points): return piecewise(points, meanY) def NNreg(points): return piecewise(points, regression) def LWR(points): return piecewise(points, lwr) def show(points): print "NNavg(x) = " + NNavg(points) print "NNreg(x) = " + NNreg(points) print "K(x, x1) = max(0, abs((x-x1)))" print "W(x, x1,y1,x2,y2,x3,y3) = (K(x,x1)*y1+K(x,x2)*y2+K(x,x3)*y3)/(K(x,x1)+K(x,x2)+K(x,x3))" print "lwr(x) = " + LWR(points) print "plot [-1:15] 'nonpar.data', 'nonpar.data' with lines, NNavg(x), NNreg(x), lwr(x)" show(points)