2015-10-06 50 views
2

Theano被赞誉之后,我想我会用一种特定形式的SGD来完成我的第一步。我有一个参数向量Theta,我想优化我的损失函数返回一个向量,其中包含矩阵A和B之间的平方损失的列总和。每个元素都是使用广播的theta的特定维度的独立损失。 Theta应该更新,以便下一次迭代每个维度的损失更低。我选择这个是因为数据(X,Y)是以这种方式给出的。Theano随着Python2.7:SGD多种损失

现在教程中说应该使用T.grad()来获取更新的渐变。但T.grad不允许我计算非标量的梯度。教程(http://deeplearning.net/software/theano/tutorial/gradients.html)说'标量成本只能由grad直接处理。数组通过重复的应用程序处理。'所以我尝试了(可以承认一个丑陋的尝试)来计算每个损失的梯度。如何计算多次损失的梯度?有没有一种干净的,最佳实践的方式?这甚至是正确的吗?我应该考虑的其他事情?

马丁

import numpy 
from theano import tensor as T 
from theano import function 
from theano import shared 

alpha = 0.00001 
theta = shared(numpy.random.rand(10), name='theta') 
X = T.dmatrix(name='X') 
Y = T.dmatrix(name='Y') 
losses = T.sqr(theta * X - Y).sum(axis=0) 

这是它是越来越怪异: 因为T.grad(亏损,THETA)抛出类型错误:成本必须是一个标量。所以,我得到了这个丑陋的尝试:

d_losses = [T.grad(losses[i], theta) for i in xrange(len(theta.get_value()))] 
updates = [(theta, theta - numpy.array(alpha) * d_losses)] 

当我想编译它,我得到这个:

>>> f = function(inputs=[A], outputs=loss, updates=updates) 
    Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/theano/compile/function.py", line 266, in function 
    profile=profile) 
    File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 489, in pfunc 
    no_default_updates=no_default_updates) 
    File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 202, in rebuild_collect_shared 
    update_val = store_into.type.filter_variable(update_val) 
    File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 206, in filter_variable 
    other = self.Constant(type=self, data=other) 
    File "/usr/local/lib/python2.7/dist-packages/theano/tensor/var.py", line 732, in __init__ 
    Constant.__init__(self, type, data, name) 
    File "/usr/local/lib/python2.7/dist-packages/theano/gof/graph.py", line 443, in __init__ 
    self.data = type.filter(data) 
    File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 115, in filter 
    up_dtype = scal.upcast(self.dtype, data.dtype) 
    File "/usr/local/lib/python2.7/dist-packages/theano/scalar/basic.py", line 67, in upcast 
    rval = str(z.dtype) 
AttributeError: 'float' object has no attribute 'dtype' 
+0

为什么你想要几次亏损?你可以有一个标量损失并得到w.r.t.到theta的每个组件。 –

+0

所以你的意思是我在xrange(len(theta.get_value())]]中的d_loss = [T.grad(loss,theta [i])?或者我会怎么做?最初的想法是,每个功能都有我自己想要捕捉的自己的损失。 –

回答

1

作为的Mikael Rousson指出了一个注释,你可能穿上”梯度的目的需要处理单独的损失;只需将所有损失分量总和为一个标量,然后根据参数向量计算偏导数,得到一个梯度向量。

所以添加

loss = losses.sum() 

或直接定义标量损失

loss = T.sqr(theta * X - Y).sum() 

然后使用

d_losses = T.grad(loss, theta) 
updates = [(theta, theta - alpha * d_losses)] 

d_losses[0]等于loss的偏导数相对于theta[0]但唯一的术语在loss那涉及theta[0]losses第一个元素之和的组成部分,所以它也等于losses[0]相对于theta[0]的偏导数,我想这正是您想要的。

+0

这是有道理的。谢谢! –