|
| 1 | +import numpy as np |
| 2 | +from theano.compat.python2x import OrderedDict |
| 3 | +from theano import function |
| 4 | +from theano import shared |
| 5 | + |
| 6 | + |
| 7 | +def make_shared(shape): |
| 8 | + """ |
| 9 | + Returns a theano shared variable containing a tensor of the specified |
| 10 | + shape. |
| 11 | + You can use any value you want. |
| 12 | + """ |
| 13 | + return shared(np.zeros(shape)) |
| 14 | + |
| 15 | + |
| 16 | +def exchange_shared(a, b): |
| 17 | + """ |
| 18 | + a: a theano shared variable |
| 19 | + b: a theano shared variable |
| 20 | + Uses get_value and set_value to swap the values stored in a and b |
| 21 | + """ |
| 22 | + temp = a.get_value() |
| 23 | + a.set_value(b.get_value()) |
| 24 | + b.set_value(temp) |
| 25 | + |
| 26 | + |
| 27 | +def make_exchange_func(a, b): |
| 28 | + """ |
| 29 | + a: a theano shared variable |
| 30 | + b: a theano shared variable |
| 31 | + Returns f |
| 32 | + where f is a theano function, that, when called, swaps the |
| 33 | + values in a and b |
| 34 | + f should not return anything |
| 35 | + """ |
| 36 | + |
| 37 | + updates = OrderedDict() |
| 38 | + updates[a] = b |
| 39 | + updates[b] = a |
| 40 | + f = function([], updates=updates) |
| 41 | + return f |
| 42 | + |
| 43 | + |
| 44 | +a = make_shared((5, 4, 3)) |
| 45 | +assert a.get_value().shape == (5, 4, 3) |
| 46 | +b = make_shared((5, 4, 3)) |
| 47 | +assert a.get_value().shape == (5, 4, 3) |
| 48 | +a.set_value(np.zeros((5, 4, 3), dtype=a.dtype)) |
| 49 | +b.set_value(np.ones((5, 4, 3), dtype=b.dtype)) |
| 50 | +exchange_shared(a, b) |
| 51 | +assert np.all(a.get_value() == 1.) |
| 52 | +assert np.all(b.get_value() == 0.) |
| 53 | +f = make_exchange_func(a, b) |
| 54 | +rval = f() |
| 55 | +assert isinstance(rval, list) |
| 56 | +assert len(rval) == 0 |
| 57 | +assert np.all(a.get_value() == 0.) |
| 58 | +assert np.all(b.get_value() == 1.) |
| 59 | + |
| 60 | +print "SUCCESS!" |
0 commit comments