gpt4 book ai didi

theano - 定期记录梯度而不需要 Theano 中的两个函数(或减速)

转载 作者:行者123 更新时间:2023-12-01 13:40:03 25 4
gpt4 key购买 nike

出于诊断目的,我定期获取网络的梯度。一种方法是将梯度作为 theano 函数的输出返回。然而,每次都将梯度从 GPU 复制到 CPU 内存可能代价高昂,所以我宁愿只定期进行。目前,我通过创建两个函数对象来实现这一点,一个返回渐变,一个不返回。

但是,我不知道这是否是最优的,我正在寻找一种更优雅的方式来实现同样的目标。

最佳答案

您的第一个函数显然执行训练步骤并更新所有参数。

第二个函数必须返回参数的梯度。

完成您要求的最快方法是将训练步骤的更新添加到第二个函数,并且在记录梯度时,不要调用第一个函数,而只调用第二个函数。

gradients = [ ... ]
train_f = theano.function([x, y], [], updates=updates)
train_grad_f = theano.function([x, y], gradients, updates=updates)
num_iters = 1000
grad_array = []
for i in range(num_iters):
# every 10 training steps keep log of gradients
if i % 10 == 0:
grad_array.append(train_grad_f(...))
else:
train_f(...)

更新

如果你希望有一个单一的功能来做到这一点,你可以这样做

from theano.ifelse import ifelse

no_grad = T.iscalar('no_grad')
example_gradient = T.grad(example_cost, example_variable)

# if no_grad is > 0 then return the gradient, otherwise return zeros array
out_grad = ifelse(T.gt(no_grad,0), example_gradient, T.zeros_like(example_variable))

train_f = theano.function([x, y, no_grad], [out_grad], updates=updates)

所以当你想检索你调用的渐变

train_f(x_data, y_data, 1)

否则

train_f(x_data, y_data, 0)

关于theano - 定期记录梯度而不需要 Theano 中的两个函数(或减速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41068057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com