我想解决以下问题: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
现在,均值(x * W / y)的梯度等于1(因为x和y总是具有相同的值)。所以第一次我应该有39.95,而不是39.90等...... 为什么我总是有相同的结果?
由于
答案 0 :(得分:0)
我是在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