本文整理汇总了Python中cupy.ndarray方法的典型用法代码示例。如果您正苦于以下问题:Python cupy.ndarray方法的具体用法?Python cupy.ndarray怎么用?Python cupy.ndarray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cupy
的用法示例。
在下文中一共展示了cupy.ndarray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_chainerx_to_cupy_delete_cupy_first
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def test_chainerx_to_cupy_delete_cupy_first():
dtype = 'float32'
a_chx = chainerx.arange(6, dtype=dtype, device='cuda:0').reshape((2, 3))
a_cupy = cupy.ndarray(
a_chx.shape,
cupy.dtype(a_chx.dtype.name),
cupy.cuda.MemoryPointer(cupy.cuda.UnownedMemory(
a_chx.data_ptr + a_chx.offset,
a_chx.data_size,
a_chx,
0), 0),
strides=a_chx.strides,
)
del a_cupy
a_chx += 1
chainerx.testing.assert_array_equal_ex(
a_chx, numpy.array([[1, 2, 3], [4, 5, 6]], dtype))
示例2: test_chainerx_to_cupy_delete_chainerx_first
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def test_chainerx_to_cupy_delete_chainerx_first():
dtype = 'float32'
a_chx = chainerx.arange(6, dtype=dtype, device='cuda:0').reshape((2, 3))
a_cupy = cupy.ndarray(
a_chx.shape,
cupy.dtype(a_chx.dtype.name),
cupy.cuda.MemoryPointer(cupy.cuda.UnownedMemory(
a_chx.data_ptr + a_chx.offset,
a_chx.data_size,
a_chx,
0), 0),
strides=a_chx.strides,
)
del a_chx
a_cupy += 1
chainerx.testing.assert_array_equal_ex(
a_cupy.get(), numpy.array([[1, 2, 3], [4, 5, 6]], dtype))
示例3: _get_device_or_current
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def _get_device_or_current(
device: tp.Optional[types.CudaDeviceSpec]
) -> Device:
# Returns cuda.Device.
# - If cuda.Device instance, it's returned intact.
# - If None, the current device is returned.
# - If non-negative integer, cuda.Device is returned.
# - Otherwise: error.
if device is None:
return cuda.Device()
if isinstance(device, Device):
return device
if not (isinstance(device, _integer_types) and device >= 0):
raise ValueError('Invalid CUDA device specifier: {}'.format(device))
return cuda.Device(int(device))
# ------------------------------------------------------------------------------
# cupy.ndarray allocation and copy
# ------------------------------------------------------------------------------
示例4: to_cpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def to_cpu(array, stream=None):
"""Copies the given GPU array to host CPU.
Args:
array (*array*, None, list or tuple):
Array or arrays to be sent to CPU.
stream (cupy.cuda.Stream): CUDA stream.
Returns:
numpy.ndarray, list or tuple: Array on CPU.
If some of the arrays are already on CPU, then this function just
returns those arrays without performing any copy.
If input arrays include `None`, it is returned as `None` as is.
"""
return _backend._convert_arrays(
array, lambda arr: _array_to_cpu(arr, stream))
示例5: __init__
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def __init__(self, numpy_object, cupy_object, array=None):
"""
_RecursiveAttr initializer.
Args:
numpy_object (method): NumPy method.
cupy_method (method): Corresponding CuPy method.
array (ndarray): Acts as flag to know if _RecursiveAttr object
is called from ``ndarray`` class. Also, acts as container for
modifying args in case it is called from ``ndarray``.
None otherwise.
"""
self._numpy_object = numpy_object
self._cupy_object = cupy_object
self._fallback_array = array
示例6: _is_cupy_compatible
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def _is_cupy_compatible(arg):
"""
Returns False if CuPy's functions never accept the arguments as
parameters due to the following reasons.
- The inputs include an object of a NumPy's specific class other than
`np.ndarray`.
- The inputs include a dtype which is not supported in CuPy.
"""
if isinstance(arg, ndarray):
if not arg._supports_cupy:
return False
if isinstance(arg, (tuple, list)):
return all([_RecursiveAttr._is_cupy_compatible(i) for i in arg])
if isinstance(arg, dict):
bools = [_RecursiveAttr._is_cupy_compatible(arg[i]) for i in arg]
return all(bools)
return True
示例7: diagonal
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def diagonal(self, k=0):
"""Returns the k-th diagonal of the matrix.
Args:
k (int, optional): Which diagonal to get, corresponding to elements
a[i, i+k]. Default: 0 (the main diagonal).
Returns:
cupy.ndarray : The k-th diagonal.
"""
rows, cols = self.shape
if k <= -rows or k >= cols:
return cupy.empty(0, dtype=self.data.dtype)
idx, = cupy.nonzero(self.offsets == k)
first_col, last_col = max(0, k), min(rows + k, cols)
if idx.size == 0:
return cupy.zeros(last_col - first_col, dtype=self.data.dtype)
return self.data[idx[0], first_col:last_col]
示例8: spdiags
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def spdiags(data, diags, m, n, format=None):
"""Creates a sparse matrix from diagonals.
Args:
data (cupy.ndarray): Matrix diagonals stored row-wise.
diags (cupy.ndarray): Diagonals to set.
m (int): Number of rows.
n (int): Number of cols.
format (str or None): Sparse format, e.g. ``format="csr"``.
Returns:
cupyx.scipy.sparse.spmatrix: Created sparse matrix.
.. seealso:: :func:`scipy.sparse.spdiags`
"""
return dia.dia_matrix((data, diags), shape=(m, n)).asformat(format)
示例9: __ua_convert__
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def __ua_convert__(dispatchables, coerce):
if coerce:
try:
replaced = [
cupy.asarray(d.value) if d.coercible and d.type is np.ndarray
else d.value for d in dispatchables]
except TypeError:
return NotImplemented
else:
replaced = [d.value for d in dispatchables]
if not all(d.type is not np.ndarray or isinstance(r, cupy.ndarray)
for r, d in zip(replaced, dispatchables)):
return NotImplemented
return replaced
示例10: ihfft
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None):
"""Compute the FFT of a signal that has Hermitian symmetry.
Args:
a (cupy.ndarray): Array to be transform.
n (None or int): Number of points along transformation axis in the
input to use. If ``n`` is not given, the length of the input along
the axis specified by ``axis`` is used.
axis (int): Axis over which to compute the FFT.
norm (None or ``"ortho"``): Keyword to specify the normalization mode.
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
plan (None): This argument is currently not supported.
Returns:
cupy.ndarray:
The transformed array which shape is specified by ``n`` and type
will convert to complex if the input is other. The length of the
transformed axis is ``n//2+1``.
.. seealso:: :func:`scipy.fft.ihfft`
"""
# TODO(leofang): support R2C & C2R plans
if plan is not None:
raise NotImplementedError('ihfft plan is currently not yet supported')
return _ihfft(x, n, axis, norm)
示例11: to_device
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def to_device(x, device_id):
if device_id is None:
return x
if device_id < 0 and isinstance(x, cupy.ndarray):
return cuda.to_cpu(x)
if device_id >= 0 and isinstance(x, numpy.ndarray):
return cuda.to_gpu(x, device_id)
return x
示例12: to_cpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def to_cpu(array):
if isinstance(array, cp.ndarray):
return cuda.to_cpu(array)
return array
示例13: _assert_allclose
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def _assert_allclose(e, a, **kwargs):
if has_cupy and isinstance(e, cupy.ndarray):
e = chainer.cuda.to_cpu(e)
a = chainer.cuda.to_cpu(a)
return chainerx.testing.assert_allclose(e, a, **kwargs)
示例14: test_numpy
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def test_numpy():
print('==========')
print('NumPy')
a_np = np.array([1, 2, 3])
b_np = np.array([4, 5, 6])
op = mobula.op.MulElemWise[np.ndarray]()
c_np = op(a_np, b_np)
print(c_np)
print('gradients:', op.backward())
示例15: test_cupy
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import ndarray [as 别名]
def test_cupy():
print('==========')
print('CuPy')
a = cp.array([1, 2, 3])
b = cp.array([4, 5, 6])
op = mobula.op.MulElemWise[cp.ndarray]()
c = op(a, b)
print(c) # [4, 10, 18]
print('gradients:', op.backward())