Python 为什么在尝试更新共享变量时会出现Theano TypeError?

Python 为什么在尝试更新共享变量时会出现Theano TypeError?,python,theano,Python,Theano,我试图在函数y=x^2上运行一个非常简单的梯度下降。 我尝试使用以下代码实现它: import theano from theano import tensor as T x = theano.shared(2) y = x ** 2 dy_dx = T.grad(y, x) learning_rate = 1 updates = [(x, x - learning_rate * dy_dx)] fn = theano.function([], [y], updates = updates)

我试图在函数y=x^2上运行一个非常简单的梯度下降。 我尝试使用以下代码实现它:

import theano
from theano import tensor as T
x = theano.shared(2)
y = x ** 2

dy_dx = T.grad(y, x)
learning_rate = 1
updates = [(x, x - learning_rate * dy_dx)]
fn = theano.function([], [y], updates = updates)
但当我尝试编译函数“fn”时,我得到以下错误:

TypeError: ('An update must have the same type as the original shared 
variable (shared_var=<TensorType(int64, scalar)>, 
shared_var.type=TensorType(int64, scalar), 
update_val=Elemwise{sub,no_inplace}.0, 
update_val.type=TensorType(float64, scalar)).', 'If the difference is 
related to the broadcast pattern, you can call the 
tensor.unbroadcast(var, axis_to_unbroadcast[, ...]) function to remove 
broadcastable dimensions.')
我仍然会犯同样的错误


我被卡住了:(有什么想法吗?

问题是您的共享变量
x
没有指定类型,因此正在推断一个类型。由于您提供的值是Python整数文本,因此该类型被假定为
int32
。这是一个问题,因为渐变不能很好地处理整数,因此
dy_dx
实际上是一个
float64de>。这反过来又使更新值成为
float64
。共享变量只能使用相同类型的值进行更新(这是错误消息),因此您有一个问题:共享变量是
int32
,但更新是
float64

一种解决方案是将共享变量也设为浮点。这可以通过简单地在
x
的初始值上添加一个小数点来实现

x = theano.shared(2.)
x = theano.shared(2.)