Skip to main content
 首页 » 编程设计

python之为什么这个 Theano.scan 函数不抛出错误

2025年05月04日14落叶无声

我有一段来自 Theano 文档的计算多项式的代码

import numpy 
import theano 
import theano.tensor as T 
 
 
theano.config.warn.subtensor_merge_bug = False 
 
coefficients = theano.tensor.vector("coefficients") 
 
x = T.scalar("x") 
 
max_coefficients_supported = 1000 
# 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], 
                                    non_sequences=x) 
 
polynomial = components.sum() 
 
calculate_polynomial = theano.function(inputs=[coefficients, x], 
outputs=polynomial) 
 
test_coeff = numpy.asarray([1, 0, 2], dtype=numpy.float32) 
print calculate_polynomial(test_coeff, 3) 

我认为它正在做的是计算 1*(3^0) + 0*(3^1) + 2*(3^2) 这是我的输出 19.0。

我的问题是 full_range 是一个包含 1000 个元素的 [0, 1, 2, ... ,998, 999] 数组。这被用作 Theano 扫描参数中的序列。

为什么不在扫描函数中添加 sequences 参数。它有两个序列作为输入,即系数和全范围。这意味着在扫描函数的每次迭代中,它都会从这些输入中的每一个中选择一个值并运行代码

coeff * (free_var ** power) 

free_var 为 3。当 coeff 中的元素数量仅为 3 而 power 中的元素数量(即 full_range 输入)有 1000 个元素时,代码如何成功运行?我在这里遗漏了一些东西。

谢谢

请您参考如下方法:

当将多个序列传递给scan时,它会根据最短序列中的元素进行迭代。

The documentation说:

given multiple sequences of uneven lengths, scan will truncate to the shortest of them. This makes it safe to pass a very long arange, which we need to do for generality, since arange must have its length specified at creation time.