diff python/utils.py @ 433:d40ad901b272

added kernel smoothing
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 29 Nov 2013 02:38:41 -0500
parents f738fa1b69f0
children 9a714f32fc9f
line wrap: on
line diff
--- a/python/utils.py	Thu Nov 28 00:48:24 2013 -0500
+++ b/python/utils.py	Fri Nov 29 02:38:41 2013 -0500
@@ -155,6 +155,47 @@
 # maths section
 #########################
 
+# def kernelSmoothing(sampleX, X, Y, weightFunc, halfwidth):
+#     '''Returns a smoothed weighted version of Y at the predefined values of sampleX
+#     Sum_x weight(sample_x,x) * y(x)'''
+#     from numpy import zeros, array
+#     smoothed = zeros(len(sampleX))
+#     for i,x in enumerate(sampleX):
+#         weights = array([weightFunc(x,xx, halfwidth) for xx in X])
+#         if sum(weights)>0:
+#             smoothed[i] = sum(weights*Y)/sum(weights)
+#         else:
+#             smoothed[i] = 0
+#     return smoothed
+
+def kernelSmoothing(x, X, Y, weightFunc, halfwidth):
+    '''Returns the smoothed estimate of (X,Y) at x
+    Sum_x weight(sample_x,x) * y(x)'''
+    from numpy import zeros, array
+    weights = array([weightFunc(x,observedx, halfwidth) for observedx in X])
+    if sum(weights)>0:
+        return sum(weights*Y)/sum(weights)
+    else:
+        return 0
+
+def uniform(center, x, halfwidth):
+    if abs(center-x)<halfwidth:
+        return 1.
+    else:
+        return 0.
+
+def gaussian(center, x, halfwidth):
+    from numpy import exp
+    return exp(-((center-x)/halfwidth)**2/2)
+
+def epanechnikov(center, x, halfwidth):
+    diff = abs(center-x)
+    if diff<halfwidth:
+        return 1.-(diff/halfwidth)**2
+    else:
+        return 0.
+    
+
 def argMaxDict(d):
     return max(d.iterkeys(), key=(lambda key: d[key]))