Theano:编译函数(GPU)内的索引

2024-09-27 23:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

由于ano只需定义需要更新的内存区域以及如何更新内存,所以我想知道下面的操作是否可行(我应该这样做)。在

我有一个2x5随机初始化的矩阵,第一列将用起始值初始化。我想写一个依赖于前一列的函数,并根据任意计算更新下一列。在

我认为这段代码很好地解释了这一点:

注意:此代码不是工作的,它只是一个示例:

from theano import function, sandbox, shared
import theano.tensor as T
import numpy as np

reservoirSize = 2
samples       = 5

            # To initialize _mat first column
_vec      = np.asarray([1 for i in range(reservoirSize)], np.float32)

            # Random matrix, first column will be initialized correctly (_vec)
_mat      = np.asarray(np.random.rand(reservoirSize, samples), np.float32)
_mat[:,0] = _vec

print "Init:\n",_mat

_mat      = shared(_mat)

idx  = T.iscalar()
test = function([idx], updates= {
            # The indexing causes the problem here. Imho there should be
            # a way to do something like this:
            #    update: _mat[:, idx] = _max[:, idx-1] * 2
            _mat[:,idx]:sandbox.cuda.basic_ops.gpu_from_host(_mat[:,idx-1] * 2) 
            })

for i in range(1, samples):
    test(i)

print "Done:\n",_mat

我想要的输出是:

^{pr2}$

但是我得到了

Init:
[[ 1. 0.62166548  0.17463242  0.00858122  0.59709388]
 [ 1. 0.52690667  0.20800008  0.86816955  0.43518791]]
Traceback (most recent call last):
  File "/home/snooc/workspace/eclipse-python/Bachelorarbeit/theano/test.py", line 20, in <module>
    _mat[:,idx]:sandbox.cuda.basic_ops.gpu_from_host(_mat[:,idx-1] * 2) })
  File "/usr/lib/python2.7/site-packages/theano/compile/function.py", line 223, in function
    profile=profile)
  File "/usr/lib/python2.7/site-packages/theano/compile/pfunc.py", line 490, in pfunc
    no_default_updates=no_default_updates)
  File "/usr/lib/python2.7/site-packages/theano/compile/pfunc.py", line 194, in rebuild_collect_shared
    store_into)
TypeError: ('update target must be a SharedVariable', Subtensor{::, int32}.0)

有人能帮我吗?在

哇:这个问题是在我问了已经在谷歌搜索结果前4名的“Theano indexing gpu”之后的9分钟。欧欧


Tags: infrompyimportnplinefunctiontheano
1条回答
网友
1楼 · 发布于 2024-09-27 23:20:01

看看:How can I assign/update subset of tensor shared variable in Theano?

对于您的代码,这转换为:

from theano import function, sandbox, shared
import theano.tensor as T
import numpy as np

reservoirSize = 2
samples       = 5

# To initialize _mat first column
_vec      = np.asarray([1 for i in range(reservoirSize)], np.float32)

# Random matrix, first column will be initialized correctly (_vec)
_mat      = np.asarray(np.random.rand(reservoirSize, samples), np.float32)
_mat[:,0] = _vec

print "Init:\n",_mat

_mat      = shared(_mat)

idx  = T.iscalar()
test = function([idx], updates= {
            # -> instead of
            #_mat[:,idx]:sandbox.cuda.basic_ops.gpu_from_host(_mat[:,idx-1] * 2)
            # -> do this:
            _mat:T.set_subtensor(_mat[:,idx], _mat[:,idx-1]*2) 
            })

for i in range(1, samples):
    test(i)

print "Done:\n",_mat.get_value()  # use get_value() here to retrieve the data

相关问题 更多 >

    热门问题