【问题标题】:Variable value change for no reason when using cupy使用cupy时变量值无故改变
【发布时间】: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


    【解决方案1】:

    这可能是因为temp 被分配给x[index]x[index] 被更改。使用 temp_value = x[index].copy() 而不是 temp_value = x[index] 作为 for 循环中的第一条语句。为此,您还需要在文件顶部添加import copy

    【讨论】:

    • 或者做你已经在不同的行中所做的事情:float(x[index]) 也会创建一个副本。
    • 非常感谢!
    猜你喜欢
    • 2017-08-08
    • 2013-05-16
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2015-03-16
    相关资源
    最近更新 更多