【问题标题】:Can not update a subset of shared tensor variable after a cast强制转换后无法更新共享张量变量的子集
【发布时间】:2015-06-05 02:19:07
【问题描述】:

我有以下代码:

import theano.tensor as T

Words = theano.shared(value = U, name = 'Words')
zero_vec_tensor = T.vector()
zero_vec = np.zeros(img_w, dtype = theano.config.floatX)
set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0,:], zero_vec_tensor))])

哪个编译得很好(其中U 是一个 dtype 的 numpy 数组float64)。

为了防止将来出现类型错误,我想将我的共享张量 Words 转换为 float32(或 theano.config.floatX,这相当于我在配置文件中将 floatX 设置为 float32)。

我添加了Words = T.cast(Words, dtype = theano.config.floatX),然后我收到以下错误:

TypeError: ('update target must be a SharedVariable', Elemwise{Cast{float32}}.0)

我不明白为什么。根据这个question,使用set_subtensor 应该允许我更新共享变量的子集。

如何在能够更新共享张量的同时投射它?

【问题讨论】:

    标签: python-2.7 numpy theano


    【解决方案1】:

    问题在于您正在尝试更新符号变量,而不是共享变量。

    U = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)
    Words = theano.shared(value=U, name='Words')
    zero_vec_tensor = T.vector()
    set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0, :], zero_vec_tensor))])
    

    工作正常,因为您要更新的东西 Words 是一个共享变量。

    U = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)
    Words = theano.shared(value=U, name='Words')
    Words = T.cast(Words, dtype = theano.config.floatX)
    zero_vec_tensor = T.vector()
    set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0, :], zero_vec_tensor))])
    

    不起作用,因为现在 Words 不再是共享变量,它是一个符号变量,执行时会将共享变量中的值转换为 theano.config.floatX

    共享变量的dtype 由分配给它的值决定。所以你可能只需要改变U的类型:

    U = np.array([[1, 2, 3], [4, 5, 6]], dtype=theano.config.floatX)
    

    或者使用 numpy 而不是象征性地投射它:

    U = np.dtype(theano.config.floatX).type(U)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多