【发布时间】: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