comparison stat_ops.py @ 326:fe57b96f33d4

made ExampleWiseMean Op
author Olivier Breuleux <breuleuo@iro.umontreal.ca>
date Fri, 13 Jun 2008 15:26:35 -0400
parents
children
comparison
equal deleted inserted replaced
325:7a734dba4cac 326:fe57b96f33d4
1
2 import theano
3 from theano import gof
4 from theano import tensor
5 import numpy
6
7
8 class ExampleWiseMean(gof.Op):
9
10 def __init__(self):
11 self.destroy_map = {0: [1, 2]}
12
13 def make_node(self, x):
14 return gof.Apply(self,
15 [x, tensor.value(float('nan')), tensor.value(0)],
16 [tensor.Tensor(dtype = 'float64',
17 broadcastable = x.type.broadcastable)()])
18
19 def perform(self, node, (x, sum, n), (out,)):
20 if numpy.isnan(sum).any():
21 sum.resize(x.shape, refcheck=0)
22 sum[:] = x
23 else:
24 sum += x
25 n += 1
26 out[0] = sum / n
27
28 def c_code(self, name, node, (x, sum, n), (out, ), sub):
29 return """
30 PyObject* multi;
31 int nelems;
32 if (isnan(((double*)(%(sum)s->data))[0])) {
33 PyArray_Dims dims;
34 dims.len = %(x)s->nd;
35 dims.ptr = %(x)s->dimensions;
36 PyArray_Resize(%(sum)s, &dims, 0, PyArray_CORDER);
37 multi = PyArray_MultiIterNew(2, %(sum)s, %(x)s);
38 nelems = PyArray_SIZE(%(sum)s);
39 while (nelems--) {
40 // Copy %(x)s in %(sum)s
41 *(double*)PyArray_MultiIter_DATA(multi, 0) = *(double*)PyArray_MultiIter_DATA(multi, 1);
42 PyArray_MultiIter_NEXT(multi);
43 }
44 }
45 else {
46 // Add some error checking on the size of x
47 multi = PyArray_MultiIterNew(2, %(sum)s, %(x)s);
48 nelems = PyArray_SIZE(%(sum)s);
49 while (nelems--) {
50 // Add %(x)s to %(sum)s
51 *(double*)PyArray_MultiIter_DATA(multi, 0) += *(double*)PyArray_MultiIter_DATA(multi, 1);
52 PyArray_MultiIter_NEXT(multi);
53 }
54 }
55 ((npy_int64*)(%(n)s->data))[0]++;
56 int n = ((npy_int64*)(%(n)s->data))[0];
57 if (%(out)s == NULL) {
58 %(out)s = (PyArrayObject*)PyArray_EMPTY(%(sum)s->nd, %(sum)s->dimensions, NPY_FLOAT64, 0);
59 }
60 multi = PyArray_MultiIterNew(2, %(sum)s, %(out)s);
61 nelems = PyArray_SIZE(%(sum)s);
62 while (nelems--) {
63 // %(out)s <- %(sum)s / %(n)s
64 *(double*)PyArray_MultiIter_DATA(multi, 1) = *(double*)PyArray_MultiIter_DATA(multi, 0) / n;
65 PyArray_MultiIter_NEXT(multi);
66 }
67 """ % dict(locals(), **sub)
68
69
70
71 if __name__ == '__main__':
72
73 vectors = numpy.random.RandomState(666).rand(10, 2)
74
75 x = tensor.dvector()
76 e = ExampleWiseMean()(x)
77
78 # f = theano.function([x], [e], linker = 'py')
79
80 # for i, v in enumerate(vectors):
81 # print v, "->", f(v), numpy.mean(vectors[:i+1], axis=0)
82
83 # print
84
85 f = theano.function([x], [e], linker = 'c|py')
86
87 for i, v in enumerate(vectors):
88 print v, "->", f(v), numpy.mean(vectors[:i+1], axis=0)
89
90
91
92