In [5]:
from theano import tensor as T
from theano import function, shared
from theano import Param

In [2]:
a, b = T.dmatrices('a', 'b')
diff = a - b
abs_diff = abs(diff)
diff_squared = diff ** 2

f = function([a, b], [diff, abs_diff, diff_squared])

print f([[1, 1], [1, 1]], [[0, 1], [2, 3]])


[array([[ 1.,  0.],
       [-1., -2.]]), array([[ 1.,  0.],
       [ 1.,  2.]]), array([[ 1.,  0.],
       [ 1.,  4.]])]

In [6]:
# -- Theano version of lambda x, y=1: x + y
x, y = T.dscalars('x', 'y')
z = x + y
f = function([x, Param(y, default=1)], z)

print f(33)
print f(33, 2)
print f(34)


34.0
35.0
35.0

In [7]:
# -- Theano version of lambda x, y=1, w_by_name=2: (x + y) * w
x, y, w = T.dscalars('x', 'y', 'w')
z = (x + y) * w
g = function([x, Param(y, default=1), Param(w, default=2, name='w_by_name')], z)
print g(33)
print g(33, 2)
print g(33, 0, 1)
print g(33, w_by_name=1)
print g(33, w_by_name=1, y=0)


68.0
70.0
33.0
34.0
33.0

In [17]:
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state, updates=[(state, state+inc)])

In [19]:
print "before - state: {}".format(state.get_value())
accumulator(2)
print "after - state: {}".format(state.get_value())


before - state: 0
after - state: 2

In [20]:
print "before - state: {}".format(state.get_value())
accumulator(2)
print "after - state: {}".format(state.get_value())


before - state: 2
after - state: 4

In [21]:
print "before - state: {}".format(state.get_value())
accumulator(2)
print "after - state: {}".format(state.get_value())


before - state: 4
after - state: 6

In [22]:
fn_of_state = state * 2 + inc
foo = T.lscalar()        # the type (lscalar) must match the shared variable we
                         # are replacing with the ``givens`` list
skip_shared = function([inc, foo], fn_of_state, givens=[(state, foo)])
print skip_shared(1, 3)  # we're using 3 for the state, not state.value
print state.get_value()  # old state still there, we didn't use it


7
6

In [ ]: