【问题标题】:Why thano does not update?为什么thano不更新?
【发布时间】:2017-10-10 09:25:37
【问题描述】:

我想解决以下问题:theano 函数将类方法返回的值作为输出值,该值在进行了一个 while 循环后,其中一个参数被更新:

import theano
import theano.tensor as T
import numpy as np
import copy
theano.config.exception_verbosity = 'high'

class Test(object):
    def __init__(self):
        self.rate=0.01
        W_val=40.00
        self.W=theano.shared(value=W_val, borrow=True)
    def start(self, x, y):
        for i in range(5):
            z=T.mean(x*self.W/y)
            gz=T.grad(z, self.W)
            self.W-=self.rate*gz
        return z

x_set=np.array([1.,2.,1.,2.,1.,2.,1.,2.,1.,2.])
y_set=np.array([1,2,1,2,1,2,1,2,1,2])
x_set = theano.shared(x_set, borrow=True)
y_set = theano.shared(y_set, borrow=True)
y_set=T.cast(y_set, 'int32')
batch_size=2

x = T.dvector('x')
y = T.ivector('y')
index = T.lscalar()

test = Test()
cost=test.start(x,y)

train = theano.function(
    inputs=[index],
    outputs=cost,
    givens={
        x: x_set[index * batch_size: (index + 1) * batch_size],
        y: y_set[index * batch_size: (index + 1) * batch_size]
    }
)

for i in range(5):
    result=train(i)
    print(result)

这是打印的结果:

39.96000000089407
39.96000000089407
39.96000000089407
39.96000000089407
39.96000000089407

现在 mean(x*W/y) 的梯度等于 1(因为 x 和 y 总是具有相同的值)。所以我第一次应该有 39.95,而不是 39.90 等等...... 为什么我总是得到相同的结果??

谢谢

【问题讨论】:

  • 在你的开始循环中。在每次迭代中,您都会覆盖您的 z 变量,这难道不是原因吗?
  • @PepaKorbel:我必须覆盖z,但是我更新了W的值,所以z的值必须改变,不是吗?
  • 哦,我仔细检查了一遍,您正在使用该 z 变量更新您的权重。那必须在其他地方
  • @PepaKorbel 是的,但在哪里?我快疯了……
  • 你的 x 和 y 张量相同吗?

标签: python python-3.x deep-learning theano


【解决方案1】:

我在来自google groups 的朋友 Pascal 的帮助下取得了成果。解决方法是创建一个其他的符号变量:

class Test(object):
    def __init__(self):
        self.rate=0.01
        W_val=40.00
        self.W=theano.shared(value=W_val, borrow=True)
    def start(self, x, y):
        new_W=self.W
        for i in range(5):
            z=T.mean(x*new_W/y)
            gz=T.grad(z, new_W)
            new_W-=self.rate*gz
        return z, (self.W, new_W)

并修改theano函数:

test = Test()
cost, updates=test.start(x,y)

train = theano.function(
    inputs=[index],
    outputs=cost,
    updates=[updates],
    givens={
        x: x_set[index * batch_size: (index + 1) * batch_size],
        y: y_set[index * batch_size: (index + 1) * batch_size]
    }
)

输出:

39.96000000089407
39.91000000201166
39.860000003129244
39.81000000424683
39.76000000536442

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2019-08-10
    • 2019-07-16
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多