【问题标题】:Difference in the array type using numpy and cupy使用numpy和cupy的数组类型的差异
【发布时间】:2019-04-24 05:05:56
【问题描述】:

我正在为我的模型使用 chainer 库并面临以下问题: 假设我有一个包含 3 个特征和一个标签(最后一列)的测试数据文件。它以列表的形式导入。 例如

test_set = [[1,0,9,1],[7,0,8,1],[7,0,2,0],[8,0,1,0]]

然后我通过将数据转换为 numpy 数组并获取标签列来获取标签, 后来我将其转换为一个列表,以便与预测的标签进行比较,比如 y_pred = [1,1,1,0]。即

import numpy as np
y_true_np = list(np.array(test_set)[:,3])
print(y_true_np)
[1, 1, 0, 0]

我担心的是,当我在 GPU 中运行我的模型时,它使用 Cuda.cupy 而不是 numpy,因为我使用的是 chainer 库,并且当我获取真实标签时,我收到它们:

在cupy那里:

import cupy as cp
y_true_cp = list(cp.array(test_set)[:,3]) Or
y_true_cp = list(cuda.cp.array(test_set)[:,3])

两者都返回一个数组列表:

y_true_cp: [array(1), array(1), array(0), array(0)]

作为一种解决方法,我在该特定位置使用 numpy。我在使用 cupy 时做错了什么,导致我没有正确获取值吗?

【问题讨论】:

    标签: python-3.x chainer cupy


    【解决方案1】:

    正如您所写,您使用list 换行时的行为似乎有所不同

    import numpy as np
    import cupy as cp
    
    print(list(np.arange(3))  # --> [0, 1, 2]
    print(list(cp.arange(3))  # --> [array(0), array(1), array(2)]
    

    但是,在您的情况下,我认为您可以只使用 numpy 数组或 cupy 数组而不转换 list

    y_true = test_set[:, 3]  # it should work for both numpy & cupy
    y_true_np = cuda.to_cpu(y_true)  # If you want to convert the array to numpy
    

    【讨论】:

      【解决方案2】:

      虽然 NumPy 将 0 维数组转换为标量,但 CuPy 不会。 https://docs-cupy.chainer.org/en/stable/reference/difference.html#zero-dimensional-array

      在结果[array(1), array(1), array(0), array(0)]中,数组的每个数据都在GPU上。如果需要高效的 CPU 阵列,我会使用 cupy.asnumpy

      y_true_cp = list(cp.asnumpy(cp.array(test_set)[:,3]))

      【讨论】:

        【解决方案3】:

        没有必要通过numpy。

        输入

        import cupy as cp
        
        test_set = [[1,0,9,1],[7,0,8,1],[7,0,2,0],[8,0,1,0]]
        test_set = cp.array(test_set)
        
        x_true = test_set[:, :3]
        y_true = test_set[:, 3]
        print("x_true:\n".format(x_true))
        print("y_true:\n".format(y_true))
        

        输出

        x_true:
        [[1 0 9]
         [7 0 8]
         [7 0 2]
         [8 0 1]]
        y_true:
        [1 1 0 0]
        

        【讨论】:

          猜你喜欢
          • 2019-12-14
          • 2017-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-13
          • 2018-11-26
          相关资源
          最近更新 更多