2015-10-20 74 views
4

我想在函數y = x^2上運行一個非常簡單的漸變下降。 我試着用下面的代碼實現它:爲什麼在嘗試更新共享變量時會遇到Theano TypeError?

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.') 

我想這可能是一個問題與learning_rate變量,因爲它可能不是同一類型的共享變量X,但如果我修改代碼如下:

updates = [(x, x - dy_dx)] 

我仍然得到同樣的錯誤。

我堅持:(任何想法?

回答

7

的問題是,你的共享變量x沒有規定這樣一個類型被推斷出來的。既然你提供的價值是一個Python整數文字,類型假設爲int32。這是一個問題,因爲漸變不適用於整數,因此dy_dx實際上是float64。這又使得更新值爲float64。共享變量只能用相同類型的值更新(這是錯誤消息),所以你有一個問題:共享變量是int32,但更新是float64

一個解決方案是使共享變量也是浮動的。這可以通過簡單地將小數點添加到初始值x來實現。

x = theano.shared(2.) 
相關問題