/doc/tutorial/loop_solution_1.py

https://github.com/lamblin/Theano
Python | 85 lines | 47 code | 24 blank | 14 comment | 0 complexity | 2ad8705ef62655e50a5b6ee6621229ee MD5 | raw file
  1. #!/usr/bin/env python
  2. # Theano tutorial
  3. # Solution to Exercise in section 'Loop'
  4. from __future__ import absolute_import, print_function, division
  5. import numpy as np
  6. import theano
  7. import theano.tensor as tt
  8. from six.moves import xrange
  9. # 1. First example
  10. theano.config.warn.subtensor_merge_bug = False
  11. k = tt.iscalar("k")
  12. A = tt.vector("A")
  13. def inner_fct(prior_result, A):
  14. return prior_result * A
  15. # Symbolic description of the result
  16. result, updates = theano.scan(fn=inner_fct,
  17. outputs_info=tt.ones_like(A),
  18. non_sequences=A, n_steps=k)
  19. # Scan has provided us with A ** 1 through A ** k. Keep only the last
  20. # value. Scan notices this and does not waste memory saving them.
  21. final_result = result[-1]
  22. power = theano.function(inputs=[A, k], outputs=final_result,
  23. updates=updates)
  24. print(power(list(range(10)), 2))
  25. # [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81.]
  26. # 2. Second example
  27. coefficients = tt.vector("coefficients")
  28. x = tt.scalar("x")
  29. max_coefficients_supported = 10000
  30. # Generate the components of the polynomial
  31. full_range = tt.arange(max_coefficients_supported)
  32. components, updates = theano.scan(fn=lambda coeff, power, free_var:
  33. coeff * (free_var ** power),
  34. sequences=[coefficients, full_range],
  35. outputs_info=None,
  36. non_sequences=x)
  37. polynomial = components.sum()
  38. calculate_polynomial1 = theano.function(inputs=[coefficients, x],
  39. outputs=polynomial)
  40. test_coeff = np.asarray([1, 0, 2], dtype=np.float32)
  41. print(calculate_polynomial1(test_coeff, 3))
  42. # 19.0
  43. # 3. Reduction performed inside scan
  44. theano.config.warn.subtensor_merge_bug = False
  45. coefficients = tt.vector("coefficients")
  46. x = tt.scalar("x")
  47. max_coefficients_supported = 10000
  48. # Generate the components of the polynomial
  49. full_range = tt.arange(max_coefficients_supported)
  50. outputs_info = tt.as_tensor_variable(np.asarray(0, 'float64'))
  51. components, updates = theano.scan(fn=lambda coeff, power, prior_value, free_var:
  52. prior_value + (coeff * (free_var ** power)),
  53. sequences=[coefficients, full_range],
  54. outputs_info=outputs_info,
  55. non_sequences=x)
  56. polynomial = components[-1]
  57. calculate_polynomial = theano.function(inputs=[coefficients, x],
  58. outputs=polynomial, updates=updates)
  59. test_coeff = np.asarray([1, 0, 2], dtype=np.float32)
  60. print(calculate_polynomial(test_coeff, 3))
  61. # 19.0