计算共享变量数组的部分梯度

3

我想要做以下事情:

import theano, numpy, theano.tensor as T

a = T.fvector('a')

w = theano.shared(numpy.array([1, 2, 3, 4], dtype=theano.config.floatX))
w_sub = w[1]

b = T.sum(a * w)

grad = T.grad(b, w_sub)

这里,w_sub是例如w[1]的变量,但我不想在函数中明确写出b。尽管我已经查看了此网页和其他相关问题,但我仍无法解决它。

这只是为了展示我的问题。实际上,我想要做的是使用Lasagne进行稀疏卷积。权重矩阵中的零元素不需要更新,因此不需要计算这些w的梯度。

这是完整的错误信息:

Traceback (most recent call last):
  File "D:/Jeroen/Project_Lasagne_General/test_script.py", line 9, in <module>
    grad = T.grad(b, w_sub)
  File "C:\Anaconda2\lib\site-packages\theano\gradient.py", line 545, in grad
    handle_disconnected(elem)
  File "C:\Anaconda2\lib\site-packages\theano\gradient.py", line 532, in handle_disconnected
    raise DisconnectedInputError(message)
theano.gradient.DisconnectedInputError: grad method was asked to compute the gradient with respect to a variable that is not part of the computational graph of the cost, or is used only by a non-differentiable operator: Subtensor{int64}.0
Backtrace when the node is created:
  File "D:/Jeroen/Project_Lasagne_General/test_script.py", line 6, in <module>
    w_sub = w[1]
1个回答

2
当Theano编译图形时,它仅将变量视为在图形中明确定义的。 在您的示例中,w_sub未在计算b时显式使用,因此不是计算图的一部分。
使用以下代码和Theano打印库,您可以在图形可视化中看到w_sub确实不是b的图形的一部分。
import theano
import theano.tensor as T
import numpy
import theano.d3viz as d3v

a = T.fvector('a')
w = theano.shared(numpy.array([1, 2, 3, 4], dtype=theano.config.floatX))
w_sub = w[1]
b = T.sum(a * w)

o = b, w_sub

d3v.d3viz(o, 'b.html')

为了解决这个问题,您需要在计算 b 时明确使用 w_sub
然后,您将能够计算 b 相对于 w_sub 的梯度,并像下面的示例一样更新共享变量的值:
import theano
import theano.tensor as T
import numpy


a = T.fvector('a')
w = theano.shared(numpy.array([1, 2, 3, 4], dtype=theano.config.floatX))
w_sub = w[1]
b = T.sum(a * w_sub)
grad = T.grad(b, w_sub)
updates = [(w, T.inc_subtensor(w_sub, -0.1*grad))]

f = theano.function([a], b, updates=updates, allow_input_downcast=True)

f(numpy.arange(10))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接