提交 681c5c64 authored 作者: Frederic's avatar Frederic

fix the loop exercice solution.

上级 283b66d5
......@@ -2,17 +2,15 @@
# Theano tutorial
# Solution to Exercise in section 'Loop'
"""
# 1. First example (runs satisfactorily)
# 1. First example
import theano
import theano.tensor as T
import theano.tensor as tensor
theano.config.warn.subtensor_merge_bug = False
k = T.iscalar("k")
A = T.vector("A")
k = tensor.iscalar("k")
A = tensor.vector("A")
def inner_fct(prior_result, A):
......@@ -20,7 +18,7 @@ def inner_fct(prior_result, A):
# Symbolic description of the result
result, updates = theano.scan(fn=inner_fct,
outputs_info=T.ones_like(A),
outputs_info=tensor.ones_like(A),
non_sequences=A, n_steps=k)
# Scan has provided us with A ** 1 through A ** k. Keep only the last
......@@ -34,22 +32,22 @@ print power(range(10), 2)
# [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81.]
# 2. Second example (runs satisfactorily)
# 2. Second example
import numpy
import theano
import theano.tensor as T
import theano.tensor as tensor
coefficients = theano.tensor.vector("coefficients")
x = T.scalar("x")
x = tensor.scalar("x")
max_coefficients_supported = 10000
# Generate the components of the polynomial
full_range = theano.tensor.arange(max_coefficients_supported)
components, updates = theano.scan(fn=lambda coeff, power, free_var:
coeff * (free_var ** power),
outputs_info=None,
sequences=[coefficients, full_range],
outputs_info=None,
non_sequences=x)
polynomial = components.sum()
calculate_polynomial1 = theano.function(inputs=[coefficients, x],
......@@ -58,33 +56,29 @@ calculate_polynomial1 = theano.function(inputs=[coefficients, x],
test_coeff = numpy.asarray([1, 0, 2], dtype=numpy.float32)
print calculate_polynomial1(test_coeff, 3)
# 19.0
"""
# 3. Reduction performed inside scan
# TODO: repair this code: yields 56.0 instead of 19.0
import numpy
import theano
import theano.tensor as T
import theano.tensor as tensor
theano.config.warn.subtensor_merge_bug = False
coefficients = theano.tensor.vector("coefficients")
x = T.scalar("x")
x = tensor.scalar("x")
max_coefficients_supported = 10000
# Generate the components of the polynomial
full_range = theano.tensor.arange(max_coefficients_supported)
outputs_info = T.as_tensor_variable(numpy.asarray(0, 'float64'))
outputs_info = tensor.as_tensor_variable(numpy.asarray(0, 'float64'))
components, updates = theano.scan(fn=lambda prior_value, coeff, power, free_var:
components, updates = theano.scan(fn=lambda coeff, power, prior_value, free_var:
prior_value + (coeff * (free_var ** power)),
outputs_info=outputs_info,
sequences=[coefficients, full_range],
outputs_info=outputs_info,
non_sequences=x)
polynomial = components[-1]
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论