【问题标题】:How does theano's scan function work?theano 的扫描功能是如何工作的?
【发布时间】:2017-08-03 15:18:12
【问题描述】:

看看这段代码:

import theano
import numpy
import theano.tensor as T 
import numpy as np

x = T.dvector('x')
y = T.dvector('y')

def fun(x,a):
    return x+a

results, updates = theano.scan(fn=fun,sequences=dict(input=x), outputs_info=dict(initial=y, taps=[-3]))

h = [10.,20,30,40,50,60,70]
f = theano.function([x, y], results)
g = theano.function([y], y)

print(f([1],h))

我已经把outputs_info'taps改成-2、-3等等,但是代码的结果还是一样的[11.0],我看不懂。谁能解释一下?

另一个问题。

import theano
import numpy
import theano.tensor as T 
import numpy as np

x = T.dvector('x')
y = T.dvector('y')

def fun(x,a,b):
    return x+a+b

results, updates = theano.scan(fn=fun,sequences=dict(input=x), outputs_info=dict(initial=y, taps=[-5,-3]))

h = [10.,20,30,40,50,60,70]
f = theano.function([x, y], results)
g = theano.function([y], y)

print(f([1,2,3,4],h))

输出是[41,62,83,85],85是怎么来的?

【问题讨论】:

标签: python theano theano.scan


【解决方案1】:

考虑您的代码的这种变化:

x = T.dvector('x')
y = T.dvector('y')

def fun(x,a,b):
    return x+b

results, updates = theano.scan(
    fn=fun,
    sequences=dict(input=x), 
    outputs_info=dict(initial=y, taps=[-5,-3])
)

h = [10.,20,30,40,50,60,70]
f = theano.function([x, y], results)
g = theano.function([y], y)

print(f([1],h))

您的结果将是 31。

  • 将点击更改为[-5, -2],您的结果将更改为 41。
  • 将点击更改为[-4, -3],您的结果将更改为 21。

这展示了事情是如何运作的:

  1. 抽头中最大的负数被视为 h[0]
  2. 所有其他抽头都从那个偏移

所以当点击为[-5,-2] 时,输入ab 分别为10 和40。

更新新问题

taps实际上表示t时刻的函数依赖于t - taps时刻函数的输出。

例如,斐波那契数列由函数定义

以下是使用theano.scan 实现斐波那契数列的方法:

x = T.ivector('x')
y = T.ivector('y')

def fibonacci(x,a,b):
    return a+b

results, _ = theano.scan(
    fn=fibonacci,
    sequences=dict(input=x), 
    outputs_info=dict(initial=y, taps=[-2,-1])
    )

h = [1,1]
f = theano.function([x, y], results)

print(np.append(h, f(range(10),h)))

但是,theano.scan 有问题。如果函数依赖于先验输出,那么第一次迭代的先验输出是什么?

答案是初始输入,在您的情况下为h。但是在您的情况下,h 比您需要的要长,您只需要将它的长度设为 5 个元素(因为在您的情况下,最大的抽头是 -5)。使用h 所需的 5 个元素后,您的函数将切换到函数的实际输出。

这是代码中发生的事情的简化跟踪:

  1. output[0] = x[0] + h[0] + h[2] = 41
  2. output[1] = x[1] + h[1] + h[3] = 62
  3. output[2] = x[2] + h[2] + h[4] = 83
  4. output[3] = x[3] + h[3] + output[0] = 85

您会看到,在时间 = 4 时,函数有一个时间 4-3 的输出,该输出为 41。既然我们有该输出,我们需要使用它,因为函数已定义就像使用先前的输出一样。所以我们忽略h 的其余部分。

【讨论】:

  • 非常感谢,我明白了。
  • 还有一个问题,你能帮帮我吗?看版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多