首页 文章

索引为theano tensor变量中的单个元素赋值

提问于
浏览
0

Theano不支持索引分配 . 好的,但有

theano.tensor.set_subtensor(x,y)

它是stated

如果你想做[5] = b或[5] = b之类的事情,请参阅下面的theano.tensor.set_subtensor()和theano.tensor.inc_subtensor() .

那么set_subtensor模拟索引赋值操作呢?嗯,不太好 . set_subtensor,在ndims <2时似乎只能按预期工作,如下例所示 .

>>> a = theano.tensor.zeros(10)
>>> a.eval()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.], dtype=float32)
>>> aa = theano.tensor.set_subtensor(a[5], 5.0)
>>> aa.eval()
array([ 0.,  0.,  0.,  0.,  0.,  5.,  0.,  0.,  0.,  0.], dtype=float32)

很酷,a.shape == aa.shape,可以设置a = aa来复制a [5] = 5.0让我们尝试更多的暗淡然后 .

>>> b = theano.tensor.zeros((5,5))
>>> b.eval()
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]], dtype=float32)
>>> bb = theano.tensor.set_subtensor(b[2][2], 5.0)
>>> bb.eval()
array([ 0.,  0.,  5.,  0.,  0.], dtype=float32)
>>> bb.shape.eval()
array([5])

虽然set_subtensor确实在目标索引处分配了指定的值,但它不返回整个更新的张量变量,而只返回具有更新值的子指定器 .

有没有人知道如何使用ndims> = 2将索引赋值给theano张量中的单个元素?

1 回答

  • 0

    能够搞清楚 . 为了在ndims> = 2的张量中为单个元素索引赋值,看起来你需要递归set_subtensor subtensor,其中包含更新后的dims值 . 例如:

    >>> b = theano.tensor.zeros((5,5))
    >>> b.eval()
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]], dtype=float32)
    >>> bb = theano.tensor.set_subtensor(b[2][2], 5.0)
    >>> bb.eval()
    array([ 0.,  0.,  5.,  0.,  0.], dtype=float32)
    >>> b = theano.tensor.set_subtensor(b[2], bb)
    >>> b.eval()
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  5.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]], dtype=float32)
    

    ndims = 3

    >>> c = theano.tensor.zeros((2,2,2))
    >>> c.eval()
    array([[[ 0.,  0.],
            [ 0.,  0.]],
    
           [[ 0.,  0.],
            [ 0.,  0.]]], dtype=float32)
    >>> ccc = theano.tensor.set_subtensor(c[0][0][0], 5.0)
    >>> ccc.eval()
    array([ 5.,  0.], dtype=float32)
    >>> cc = theano.tensor.set_subtensor(c[0][0], ccc)
    >>> cc.eval()
    array([[ 5.,  0.],
           [ 0.,  0.]], dtype=float32)
    >>> c = theano.tensor.set_subtensor(c[0], cc)
    >>> c.eval()
    array([[[ 5.,  0.],
            [ 0.,  0.]],
    
           [[ 0.,  0.],
           [ 0.,  0.]]], dtype=float32)
    

    也许有一种更简单/更快捷的索引分配方式,但这就是我发现的 .

相关问题