【问题标题】:Troubles with simple accumulation with Theano scan function使用 Theano 扫描功能进行简单累积的问题
【发布时间】:2015-11-02 18:41:53
【问题描述】:

我试图在与步骤相乘的同时累积矩阵值: res = sum_i(i * a)。我的代码如下所示:

import numpy as np
from theano import function, scan
import theano.tensor as T

x = T.lmatrix()
results, updates = scan(
    lambda res, step, x: res + step * x, 
    non_sequences=x,
    sequences=T.arange(2),
    outputs_info=T.zeros_like(x))

f = function([x], results)
a = np.array([[0, 0], [2, 2]], 'int64')
print(f(a))

这个输出:

[[[0 0]
  [0 0]]

[[1 1]
 [1 1]]]

虽然我希望这样:

[[[0 0]
  [0 0]]

[[0 0]
 [2 2]]]

【问题讨论】:

  • 我提供了一个答案,解释了为什么你得到了你实际得到的输出,但不能评论为什么这与你的期望不同,因为不清楚 为什么 你期望输出[[[0 0] [0 0]] [[0 0] [2 2]]]。如果您用更多关于您的期望的信息更新问题,我也许可以用更多信息更新我的答案。

标签: theano


【解决方案1】:

输出是正确的(也许不足为奇?)。得到这个输出的原因如下:

在第一次迭代中,

res = 0
step = [[0, 0], [0, 0]]
x = [[0, 0], [2, 2]]

等等

res + step * x = 0 + [[0, 0], [0, 0]] * [[0, 0], [2, 2]]
               = 0 + [[0, 0], [0, 0]]
               = [[0, 0], [0, 0]]

在第二次迭代中,

res = 1
step = [[0, 0], [0, 0]]
x = [[0, 0], [2, 2]]

等等

res + step * x = 1 + [[0, 0], [0, 0]] * [[0, 0], [2, 2]]
               = 1 + [[0, 0], [0, 0]]
               = [[1, 1], [1, 1]]

请注意,1 被广播为与 stepx 的元素乘法得到的矩阵相同的形状。

【讨论】:

  • 感谢您的洞察力。我现在明白我的错误了。 lambda 函数中参数的顺序与我假设的不同。应该是lambda step, res, x: res + step * x
  • 它有助于保持传递给 step 函数的参数的顺序,以反映这些参数类型传递给 step 函数的顺序。所以使用scan(sequences=[...], outputs_info=[...], non_sequences=[...]),因为阶梯函数总是首先给出序列,然后是循环值(outputs_info),最后是非序列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多