gpt4 book ai didi

python - Theano set_value 用于强制转换的共享变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:11 26 4
gpt4 key购买 nike

在Theano深度学习教程中,y是一个强制转换的共享变量:

   y = theano.shared(numpy.asarray(data, dtype=theano.config.floatX))
y = theano.tensor.cast(y, 'int32')

稍后我想为 y 设置一个新值。

对于 GPU 这可行:

    y.owner.inputs[0].owner.inputs[0].set_value(np.asarray(data2, dtype=theano.config.floatX))

对于 CPU 这可行:

    y.owner.inputs[0].set_value(np.asarray(data2, dtype=theano.config.floatX))

为什么这需要在 GPU 和 CPU 之间使用不同的语法?我希望我的代码适用于这两种情况,我做错了吗?

最佳答案

这与另一个 StackOverflow question 中描述的问题非常相似.

问题是您正在使用一个符号转换操作,它将共享变量变成一个符号变量。

解决方案是转换共享变量的值而不是共享变量本身。

代替

y = theano.shared(numpy.asarray(data, dtype=theano.config.floatX))
y = theano.tensor.cast(y, 'int32')

使用

y = theano.shared(numpy.asarray(data, dtype='int32'))

通过 owner 属性导航 Theano 计算图被认为是错误的形式。如果要更改共享变量的值,请维护对共享变量的 Python 引用并直接设置其值。

因此,由于 y 只是一个共享变量,而不是符号变量,您现在可以这样做:

y.set_value(np.asarray(data2, dtype='int32'))

请注意,转换再次发生在 numpy 中,而不是 Theano。

关于python - Theano set_value 用于强制转换的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31025226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com