在cupy中不需要时尝试numpy转换



使用python3.8和cupy-cuda111

创建一个cupy数组并尝试强制转换为cp.int会导致cupy假定隐式转换为numpy数组

import cupy as cp
def test_function(x):
y = cp.int_(x * 10)
return(y)
x = cp.array([0.1, 0.2, 0.3, 0.4, 0.5])
y = test_function(x)
print(y)

我假设这将乘以标量并返回([1, 2, 3, 4, 5], dtype=cp.int_)而是给出:

TypeError: Implicit conversion to a NumPy array is not allowed. Please use `.get()` to construct a NumPy array explicitly.

为什么会生成此错误?

如何将cp.array相乘并强制转换为int_?

您可以进行

x = x * 10
y = x.astype(cp.int_)
return y

问题是cp.int_就是np.int_,所以调用它会调用一个主机函数在GPU阵列上操作,这是不允许的。

现在,数据在GPU中操作,您可以通过设备功能在GPU或CPU中检查数据。

错误显示,您可以通过get((函数将其转换为CPU,然后,通过type((函数检查数据的类型,会发现它是numpy.ndarray,但不是cupy.core.ndarray

最后:

def test_function(x):
y = (x * 10).astype(cp.int_)
return y

最新更新