theano5_function.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # View more python tutorials on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. # 5 - theano.function
  5. """
  6. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
  7. """
  8. from __future__ import print_function
  9. import numpy as np
  10. import theano
  11. import theano.tensor as T
  12. # activation function example
  13. x = T.dmatrix('x')
  14. s = 1 / (1 + T.exp(-x)) # logistic or soft step
  15. logistic = theano.function([x], s)
  16. print(logistic([[0, 1],[-1, -2]]))
  17. # multiply outputs for a function
  18. a, b = T.dmatrices('a', 'b')
  19. diff = a - b
  20. abs_diff = abs(diff)
  21. diff_squared = diff ** 2
  22. f = theano.function([a, b], [diff, abs_diff, diff_squared])
  23. print( f(np.ones((2, 2)), np.arange(4).reshape((2, 2))) )
  24. # default value and name for a function
  25. x, y, w = T.dscalars('x', 'y', 'w')
  26. z = (x+y)*w
  27. f = theano.function([x,
  28. theano.In(y, value=1),
  29. theano.In(w, value=2, name='weights')],
  30. z)
  31. print(f(23, 2, weights=4))