我正在使用Tensorflow后端测试Keras,并试图更好地理解张量变量是如何工作的。我修改了Keras的随机梯度下降的更新函数,看看是否可以将值从一个变量复制到另一个变量。
目前我不能,但不知道为什么。
我已经修改了
get_updates
方法来创建
params
变量,用于存储网络的权重和偏差。我以与原件相同的方式更新此副本。当我使用副本的更新值更新原始文件时,不会出现任何要更新的值。当我使用原始文件的更新值更新原始文件时,更新是有效的。我不知道为什么一个案例有效,另一个不有效。
以下是修改后的版本
获取最新信息
方法我提供了更新params变量的常规(合理)方法,并展示了如何使用副本进行更新。
@interfaces.legacy_get_updates_support
def get_updates(self, loss, params):
# Copy parameters - Create copy of net parameters
params_tmp = []
for p in params:
params_tmp.append(K.variable(K.get_value(p), name=p.name[:-2] + "_cpy/"))
self.updates = [K.update_add(self.iterations, 1)]
self.weights = [self.iterations]
grads = self.get_gradients(loss, params) # Get Initial Gradient
# for Heun
for p, p_tmp, g in zip(params, params_tmp, grads):
v = - self.lr * g
new_p = p + v
new_p_tmp = p_tmp + v # Getting intermediate update
# using first gradient from Heun
# Apply constraints.
if getattr(p, 'constraint', None) is not None:
new_p = p.constraint(new_p)
if getattr(p_tmp, 'constraint', None) is not None:
new_p_tmp = p_tmp.constraint(new_p_tmp)
# Copy completed Heun update back to original param
self.updates.append(K.update(p, new_p_tmp)) # Doesnt Work
#self.updates.append(K.update(p, new_p)) # Works
return self.updates
对于Tensorflow、Keras,更新函数为
def update(x, new_x):
"""Update the value of `x` to `new_x`.
# Arguments
x: A `Variable`.
new_x: A tensor of same shape as `x`.
# Returns
The variable `x` updated.
"""
return tf.assign(x, new_x)
为什么我不能使用副本的更新值更新params变量?