【发布时间】:2020-06-24 15:15:58
【问题描述】:
我正在使用 cupy 实现机器学习的梯度公式。但是,我遇到了一个奇怪的错误,其中变量 temp_value 无缘无故地发生了变化。 这是我的代码:
import cupy as cp
def gradient_1d(f, x):
grad = cp.zeros_like(x)
h = 0.00001
for index in range(x.size):
temp_value = x[index]
print(temp_value,'1')
x[index] = float(temp_value) + h
print(temp_value,'2')
plus_result = f(x)
print(temp_value,'3')
x[index] = temp_value - h
print(temp_value,'4')
minus_result = f(x)
print(temp_value,'5')
grad[index] = ((plus_result - minus_result)/2*h)
print(temp_value,'6')
x[index] = temp_value
return grad
def f2(x):
if x.ndim == 1:
return cp.sum(x**2)
else:
return cp.sum(x**2, axis=1)
def main():
x = cp.array([1, 2])
grad = gradient_2d(f2, x)
print(grad)
main()
输出是:
1 1
1 2
1 3
0 4
0 5
0 6
2 1
2 2
2 3
1 4
1 5
1 6
[0 0]
您可以观察到 temp_value 的值在每次到达第 4 个检查点时都会减少 1,但我没有做任何更新此变量的操作。
为什么??? 提前感谢您的帮助!
【问题讨论】:
标签: python machine-learning gradient cupy