cupy.ndarray — CuPy 13.4.1 documentation (original) (raw)

class cupy.ndarray(self, shape, dtype=float, memptr=None, strides=None, order='C')[source]#

Multi-dimensional array on a CUDA device.

This class implements a subset of methods of numpy.ndarray. The difference is that this class allocates the array content on the current GPU device.

Parameters:

Variables:

Methods

__getitem__()#

x.__getitem__(y) <==> x[y]

Supports both basic and advanced indexing.

Note

Currently, it does not support slices that consists of more than one boolean arrays

Note

CuPy handles out-of-bounds indices differently from NumPy. NumPy handles them by raising an error, but CuPy wraps around them.

Example

a = cupy.arange(3) a[[1, 3]] array([1, 0])

__setitem__()#

x.__setitem__(slices, y) <==> x[slices] = y

Supports both basic and advanced indexing.

Note

Currently, it does not support slices that consists of more than one boolean arrays

Note

CuPy handles out-of-bounds indices differently from NumPy when using integer array indexing. NumPy handles them by raising an error, but CuPy wraps around them.

import cupy x = cupy.arange(3) x[[1, 3]] = 10 x array([10, 10, 2])

Note

The behavior differs from NumPy when integer arrays in slicesreference the same location multiple times. In that case, the value that is actually stored is undefined.

import cupy a = cupy.zeros((2,)) i = cupy.arange(10000) % 2 v = cupy.arange(10000).astype(cupy.float64) a[i] = v a
array([9150., 9151.])

On the other hand, NumPy stores the value corresponding to the last index among the indices referencing duplicate locations.

import numpy a_cpu = numpy.zeros((2,)) i_cpu = numpy.arange(10000) % 2 v_cpu = numpy.arange(10000).astype(numpy.float64) a_cpu[i_cpu] = v_cpu a_cpu array([9998., 9999.])

__len__()#

Return len(self).

__iter__()#

Implement iter(self).

__copy__(self)#

all(self, axis=None, out=None, keepdims=False) → ndarray#

any(self, axis=None, out=None, keepdims=False) → ndarray#

argmax(self, axis=None, out=None, dtype=None, keepdims=False) → ndarray#

Returns the indices of the maximum along a given axis.

Note

dtype and keepdim arguments are specific to CuPy. They are not in NumPy.

Note

axis argument accepts a tuple of ints, but this is specific to CuPy. NumPy does not support it.

argmin(self, axis=None, out=None, dtype=None, keepdims=False) → ndarray#

Returns the indices of the minimum along a given axis.

Note

dtype and keepdim arguments are specific to CuPy. They are not in NumPy.

Note

axis argument accepts a tuple of ints, but this is specific to CuPy. NumPy does not support it.

argpartition(self, kth, axis=-1) → ndarray#

Returns the indices that would partially sort an array.

Parameters:

Returns:

Array of the same type and shape as a.

Return type:

cupy.ndarray

argsort(self, axis=-1) → ndarray#

Returns the indices that would sort an array with stable sorting

Parameters:

axis (int or None) – Axis along which to sort. Default is -1, which means sort along the last axis. If None is supplied, the array is flattened before sorting.

Returns:

Array of indices that sort the array.

Return type:

cupy.ndarray

astype(self, dtype, order='K', casting=None, subok=None, copy=True) → ndarray#

Casts the array to given data type.

Parameters:

Returns:

If copy is False and no cast is required, then the array itself is returned. Otherwise, it returns a (possibly casted) copy of the array.

Note

This method currently does not support casting, and subokarguments.

choose(self, choices, out=None, mode='raise')#

clip(self, min=None, max=None, out=None) → ndarray#

Returns an array with values limited to [min, max].

compress(self, condition, axis=None, out=None) → ndarray#

Returns selected slices of this array along given axis.

Warning

This function may synchronize the device.

conj(self) → ndarray#

conjugate(self) → ndarray#

copy(self, order='C') → ndarray#

Returns a copy of the array.

This method makes a copy of a given array in the current device. Even when a given array is located in another device, you can copy it to the current device.

Parameters:

order ({'C' , 'F' , 'A' , 'K'}) – Row-major (C-style) or column-major (Fortran-style) order. When order is ‘A’, it uses ‘F’ if a is column-major and uses ‘C’ otherwise. And when order is ‘K’, it keeps strides as closely as possible.

cumprod(self, axis=None, dtype=None, out=None) → ndarray#

Returns the cumulative product of an array along a given axis.

cumsum(self, axis=None, dtype=None, out=None) → ndarray#

Returns the cumulative sum of an array along a given axis.

diagonal(self, offset=0, axis1=0, axis2=1) → ndarray#

Returns a view of the specified diagonals.

dot(self, ndarray b, ndarray out=None)#

Returns the dot product with given array.

dump(self, file)#

Dumps a pickle of the array to a file.

Dumped file can be read back to cupy.ndarray bycupy.load().

dumps(self) → bytes#

Dumps a pickle of the array to a string.

fill(self, value)#

Fills the array with a scalar value.

Parameters:

value – A scalar value to fill the array content.

flatten(self, order='C') → ndarray#

Returns a copy of the array flatten into one dimension.

Parameters:

order ({'C' , 'F' , 'A' , 'K'}) – ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if self is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flattenself in the order the elements occur in memory. The default is ‘C’.

Returns:

A copy of the array with one dimension.

Return type:

cupy.ndarray

get(self, stream=None, order='C', out=None, blocking=True)#

Returns a copy of the array on host memory.

Parameters:

Returns:

Copy of the array on host memory.

Return type:

numpy.ndarray

item(self)#

Converts the array with one element to a Python scalar

Returns:

The element of the array.

Return type:

int or float or complex

max(self, axis=None, out=None, keepdims=False) → ndarray#

Returns the maximum along a given axis.

mean(self, axis=None, dtype=None, out=None, keepdims=False) → ndarray#

Returns the mean along a given axis.

min(self, axis=None, out=None, keepdims=False) → ndarray#

Returns the minimum along a given axis.

nonzero(self) → tuple#

Return the indices of the elements that are non-zero.

Returned Array is containing the indices of the non-zero elements in that dimension.

Returns:

Indices of elements that are non-zero.

Return type:

tuple of arrays

Warning

This function may synchronize the device.

partition(self, kth, int axis=-1)#

Partitions an array.

Parameters:

prod(self, axis=None, dtype=None, out=None, keepdims=None) → ndarray#

Returns the product along a given axis.

ptp(self, axis=None, out=None, keepdims=False) → ndarray#

Returns (maximum - minimum) along a given axis.

See also

cupy.ptp() for full documentation,numpy.ndarray.ptp()

put(self, indices, values, mode='wrap')#

Replaces specified elements of an array with given values.

ravel(self, order='C') → ndarray#

Returns an array flattened into one dimension.

reduced_view(self, dtype=None) → ndarray#

Returns a view of the array with minimum number of dimensions.

Parameters:

dtype – (Deprecated) Data type specifier. If it is given, then the memory sequence is reinterpreted as the new type.

Returns:

A view of the array with reduced dimensions.

Return type:

cupy.ndarray

repeat(self, repeats, axis=None)#

Returns an array with repeated arrays along an axis.

reshape(self, *shape, order='C')#

Returns an array of a different shape and the same content.

round(self, decimals=0, out=None) → ndarray#

Returns an array with values rounded to the given number of decimals.

scatter_add(self, slices, value)#

Adds given values to specified elements of an array.

scatter_max(self, slices, value)#

Stores a maximum value of elements specified by indices to an array.

scatter_min(self, slices, value)#

Stores a minimum value of elements specified by indices to an array.

searchsorted(self, v, side='left', sorter=None)#

Finds indices where elements of v should be inserted to maintain order.

For full documentation, see cupy.searchsorted()

Returns:

set(self, arr, stream=None)#

Copies an array on the host memory to cupy.ndarray.

Parameters:

sort(self, int axis=-1)#

Sort an array, in-place with a stable sorting algorithm.

Parameters:

axis (int) – Axis along which to sort. Default is -1, which means sort along the last axis.

Note

For its implementation reason, ndarray.sort currently supports only arrays with their own data, and does not support kind andorder parameters that numpy.ndarray.sort does support.

squeeze(self, axis=None) → ndarray#

Returns a view with size-one axes removed.

std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False) → ndarray#

Returns the standard deviation along a given axis.

sum(self, axis=None, dtype=None, out=None, keepdims=False) → ndarray#

Returns the sum along a given axis.

swapaxes(self, Py_ssize_t axis1, Py_ssize_t axis2) → ndarray#

Returns a view of the array with two axes swapped.

take(self, indices, axis=None, out=None) → ndarray#

Returns an array of elements at given indices along the axis.

toDlpack(self)#

Zero-copy conversion to a DLPack tensor.

DLPack is a open in memory tensor structure proposed in this repository: dmlc/dlpack.

This function returns a PyCapsule object which contains a pointer to a DLPack tensor converted from the own ndarray. This function does not copy the own data to the output DLpack tensor but it shares the pointer which is pointing to the same memory region for the data.

Returns:

Output DLPack tensor which is encapsulated in a PyCapsule object.

Return type:

dltensor (PyCapsule)

See also

fromDlpack() is a method for zero-copy conversion from a DLPack tensor (which is encapsulated in a PyCapsuleobject) to a ndarray

Warning

As of the DLPack v0.3 specification, it is (implicitly) assumed that the user is responsible to ensure the Producer and the Consumer are operating on the same stream. This requirement might be relaxed/changed in a future DLPack version.

Example

import cupy array1 = cupy.array([0, 1, 2], dtype=cupy.float32) dltensor = array1.toDlpack() array2 = cupy.fromDlpack(dltensor) cupy.testing.assert_array_equal(array1, array2)

tobytes(self, order='C') → bytes#

Turns the array into a Python bytes object.

tofile(self, fid, sep='', format='%s')#

Writes the array to a file.

tolist(self)#

Converts the array to a (possibly nested) Python list.

Returns:

The possibly nested Python list of array elements.

Return type:

list

trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None) → ndarray#

Returns the sum along diagonals of the array.

transpose(self, *axes)#

Returns a view of the array with axes permuted.

var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False) → ndarray#

Returns the variance along a given axis.

view(self, dtype=None, type=None)#

Returns a view of the array.

Parameters:

dtype – If this is different from the data type of the array, the returned view reinterpret the memory sequence as an array of this type.

Returns:

A view of the array. A reference to the original array is stored at the base attribute.

Return type:

cupy.ndarray

__eq__(value, /)#

Return self==value.

__ne__(value, /)#

Return self!=value.

__lt__(value, /)#

Return self<value.

__le__(value, /)#

Return self<=value.

__gt__(value, /)#

Return self>value.

__ge__(value, /)#

Return self>=value.

__bool__()#

True if self else False

Attributes

T#

Shape-reversed view of the array.

If ndim < 2, then this is just a reference to the array itself.

base#

cstruct#

C representation of the array.

This property is used for sending an array to CUDA kernels. The type of returned C structure is different for different dtypes and ndims. The definition of C type is written in cupy/carray.cuh.

data#

device#

CUDA device on which this array resides.

dtype#

flags#

Object containing memory-layout information.

It only contains c_contiguous, f_contiguous, and owndataattributes. All of these are read-only. Accessing by indexes is also supported.

flat#

imag#

itemsize#

Size of each element in bytes.

nbytes#

Total size of all elements in bytes.

It does not count skips between elements.

ndim#

Number of dimensions.

a.ndim is equivalent to len(a.shape).

real#

shape#

Lengths of axes.

Setter of this property involves reshaping without copy. If the array cannot be reshaped without copy, it raises an exception.

size#

strides#

Strides of axes in bytes.