給定一個 CuPy 陣列a,有兩種方法可以從中獲取一個 numpy 陣列:a.get()和cupy.asnumpy(a). 它們之間有什么實際區別嗎?
import cupy as cp
a = cp.random.randint(10, size=(4,5,6,7))
b = a.get()
c = cp.asnumpy(a)
assert type(b) == type(c) and (b == c).all()
uj5u.com熱心網友回復:
cp.asnumpy是一個包裝呼叫ndarray.get. 您可以在以下代碼中看到cp.asnumpy:
def asnumpy(a, stream=None, order='C', out=None):
"""Returns an array on the host memory from an arbitrary source array.
Args:
a: Arbitrary object that can be converted to :class:`numpy.ndarray`.
stream (cupy.cuda.Stream): CUDA stream object. If it is specified, then
the device-to-host copy runs asynchronously. Otherwise, the copy is
synchronous. Note that if ``a`` is not a :class:`cupy.ndarray`
object, then this argument has no effect.
order ({'C', 'F', 'A'}): The desired memory layout of the host
array. When ``order`` is 'A', it uses 'F' if ``a`` is
fortran-contiguous and 'C' otherwise.
out (numpy.ndarray): The output array to be written to. It must have
compatible shape and dtype with those of ``a``'s.
Returns:
numpy.ndarray: Converted array on the host memory.
"""
if isinstance(a, ndarray):
return a.get(stream=stream, order=order, out=out)
elif hasattr(a, "__cuda_array_interface__"):
return array(a).get(stream=stream, order=order, out=out)
else:
temp = _numpy.asarray(a, order=order)
if out is not None:
out[...] = temp
else:
out = temp
return out
如您所見(在檔案和代碼中),cp.asnumpy支持的輸入型別不僅僅是 CuPy 陣列。它支持作為具有屬性的 CUDA 物件的輸入,__cuda_array_interface__以及任何可以實際轉換為 Numpy 陣列的物件。這包括 Numpy 陣列本身和可迭代物件(例如串列、生成器等)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473657.html
