CuPy: NumPy & SciPy for GPU - A NumPy/SciPy-compatible array library for GPU-accelerated computing with Python, specifically built for CUDA 11.1
—
Comprehensive array creation, manipulation, and transformation functions that mirror NumPy's API while providing GPU acceleration. These operations form the foundation of CuPy's array programming capabilities.
Create arrays with specific shapes, values, and data types on GPU memory.
def zeros(shape, dtype=float, order='C'):
"""
Create array filled with zeros.
Parameters:
- shape: int or sequence of ints, shape of new array
- dtype: data type, optional (default: float)
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: Array of given shape and type filled with zeros
"""
def ones(shape, dtype=None, order='C'):
"""
Create array filled with ones.
Parameters:
- shape: int or sequence of ints
- dtype: data type, optional
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: Array filled with ones
"""
def empty(shape, dtype=float, order='C'):
"""
Create uninitialized array.
Parameters:
- shape: int or sequence of ints
- dtype: data type, optional
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: Uninitialized array
"""
def full(shape, fill_value, dtype=None, order='C'):
"""
Create array filled with fill_value.
Parameters:
- shape: int or sequence of ints
- fill_value: scalar, fill value
- dtype: data type, optional
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: Array filled with fill_value
"""
def eye(N, M=None, k=0, dtype=float, order='C'):
"""
Create 2D identity matrix.
Parameters:
- N: int, number of rows
- M: int, optional, number of columns (default: N)
- k: int, optional, diagonal offset (default: 0)
- dtype: data type
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: 2D array with ones on diagonal
"""Convert existing data to CuPy arrays or create arrays with specific patterns.
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""
Create array from array-like object.
Parameters:
- obj: array_like, input data
- dtype: data type, optional
- copy: bool, whether to copy data
- order: {'K', 'A', 'C', 'F'}, memory layout
- subok: bool, whether to return subclass
- ndmin: int, minimum dimensions
Returns:
- ndarray: Array interpretation of input
"""
def asarray(a, dtype=None, order=None):
"""
Convert input to array.
Parameters:
- a: array_like, input data
- dtype: data type, optional
- order: {'C', 'F'}, memory layout
Returns:
- ndarray: Array interpretation of a
"""
def ascontiguousarray(a, dtype=None):
"""
Return contiguous array in C order.
Parameters:
- a: array_like, input array
- dtype: data type, optional
Returns:
- ndarray: Contiguous array
"""
def copy(a, order='K', subok=False):
"""
Return copy of array.
Parameters:
- a: array_like, input array
- order: {'C', 'F', 'A', 'K'}, memory layout
- subok: bool, preserve subclass
Returns:
- ndarray: Copy of input array
"""Create arrays with evenly spaced values, coordinate grids, and structured patterns.
def arange(start, stop=None, step=1, dtype=None):
"""
Create array with evenly spaced values.
Parameters:
- start: number, start of interval
- stop: number, optional, end of interval
- step: number, spacing between values
- dtype: data type, optional
Returns:
- ndarray: Array of evenly spaced values
"""
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
"""
Create array with evenly spaced values over interval.
Parameters:
- start: scalar, start of sequence
- stop: scalar, end of sequence
- num: int, number of samples
- endpoint: bool, include endpoint
- retstep: bool, return step size
- dtype: data type, optional
- axis: int, axis in result to store samples
Returns:
- ndarray: Array of evenly spaced samples
- float: Step size (if retstep=True)
"""
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
"""
Create array with logarithmically spaced values.
Parameters:
- start: scalar, base**start is starting value
- stop: scalar, base**stop is final value
- num: int, number of samples
- endpoint: bool, include endpoint
- base: scalar, base of log space
- dtype: data type, optional
- axis: int, axis in result
Returns:
- ndarray: Logarithmically spaced samples
"""
def meshgrid(*xi, **kwargs):
"""
Create coordinate matrices from coordinate vectors.
Parameters:
- *xi: array_like, 1D coordinate arrays
- copy: bool, return copies
- sparse: bool, return sparse grid
- indexing: {'xy', 'ij'}, indexing convention
Returns:
- list of ndarray: Coordinate matrices
"""Change array shapes, dimensions, and memory layout without copying data when possible.
def reshape(a, newshape, order='C'):
"""
Give new shape to array without changing data.
Parameters:
- a: array_like, input array
- newshape: int or tuple of ints, new shape
- order: {'C', 'F', 'A'}, read elements order
Returns:
- ndarray: Reshaped array
"""
def ravel(a, order='C'):
"""
Return flattened array.
Parameters:
- a: array_like, input array
- order: {'C', 'F', 'A', 'K'}, flatten order
Returns:
- ndarray: 1D array
"""
def flatten(a, order='C'):
"""
Return flattened copy of array.
Parameters:
- a: array_like, input array
- order: {'C', 'F', 'A', 'K'}, flatten order
Returns:
- ndarray: 1D copy of input
"""Add, remove, or rearrange array dimensions.
def expand_dims(a, axis):
"""
Expand array dimensions.
Parameters:
- a: array_like, input array
- axis: int or tuple of ints, position of new axes
Returns:
- ndarray: Array with expanded dimensions
"""
def squeeze(a, axis=None):
"""
Remove single-dimensional entries.
Parameters:
- a: array_like, input array
- axis: None or int or tuple of ints, axes to squeeze
Returns:
- ndarray: Array with squeezed dimensions
"""
def transpose(a, axes=None):
"""
Permute array dimensions.
Parameters:
- a: array_like, input array
- axes: list of ints, permutation of axes
Returns:
- ndarray: Transposed array
"""
def moveaxis(a, source, destination):
"""
Move axes of array to new positions.
Parameters:
- a: array_like, input array
- source: int or sequence of ints, original positions
- destination: int or sequence of ints, destination positions
Returns:
- ndarray: Array with moved axes
"""
def swapaxes(a, axis1, axis2):
"""
Interchange two axes of array.
Parameters:
- a: array_like, input array
- axis1: int, first axis
- axis2: int, second axis
Returns:
- ndarray: Array with swapped axes
"""Combine multiple arrays along existing or new axes.
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
"""
Join arrays along existing axis.
Parameters:
- arrays: sequence of array_like, arrays to join
- axis: int, axis along which to join
- out: ndarray, optional, destination array
- dtype: data type, optional
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
Returns:
- ndarray: Concatenated array
"""
def stack(arrays, axis=0, out=None):
"""
Join arrays along new axis.
Parameters:
- arrays: sequence of array_like, arrays to stack
- axis: int, axis along which to stack
- out: ndarray, optional, destination array
Returns:
- ndarray: Stacked array
"""
def vstack(tup):
"""
Stack arrays vertically (row-wise).
Parameters:
- tup: sequence of ndarrays, arrays to stack
Returns:
- ndarray: Stacked array
"""
def hstack(tup):
"""
Stack arrays horizontally (column-wise).
Parameters:
- tup: sequence of ndarrays, arrays to stack
Returns:
- ndarray: Stacked array
"""
def dstack(tup):
"""
Stack arrays depth-wise (along third axis).
Parameters:
- tup: sequence of ndarrays, arrays to stack
Returns:
- ndarray: Stacked array
"""Divide arrays into multiple sub-arrays.
def split(ary, indices_or_sections, axis=0):
"""
Split array into multiple sub-arrays.
Parameters:
- ary: ndarray, input array
- indices_or_sections: int or 1D array, split points
- axis: int, axis along which to split
Returns:
- list of ndarray: Sub-arrays
"""
def array_split(ary, indices_or_sections, axis=0):
"""
Split array into multiple sub-arrays (unequal division).
Parameters:
- ary: ndarray, input array
- indices_or_sections: int or 1D array, split points
- axis: int, axis along which to split
Returns:
- list of ndarray: Sub-arrays
"""
def hsplit(ary, indices_or_sections):
"""
Split array horizontally.
Parameters:
- ary: ndarray, input array
- indices_or_sections: int or 1D array, split points
Returns:
- list of ndarray: Horizontally split arrays
"""
def vsplit(ary, indices_or_sections):
"""
Split array vertically.
Parameters:
- ary: ndarray, input array
- indices_or_sections: int or 1D array, split points
Returns:
- list of ndarray: Vertically split arrays
"""Add, remove, or modify array elements and structure.
def append(arr, values, axis=None):
"""
Append values to end of array.
Parameters:
- arr: array_like, input array
- values: array_like, values to append
- axis: int, optional, axis to append along
Returns:
- ndarray: Array with appended values
"""
def resize(a, new_shape):
"""
Return new array with specified shape.
Parameters:
- a: array_like, input array
- new_shape: int or tuple of ints, new shape
Returns:
- ndarray: Resized array
"""
def repeat(a, repeats, axis=None):
"""
Repeat elements of array.
Parameters:
- a: array_like, input array
- repeats: int or array of ints, number of repetitions
- axis: int, optional, axis along which to repeat
Returns:
- ndarray: Array with repeated elements
"""
def tile(A, reps):
"""
Construct array by repeating A.
Parameters:
- A: array_like, input array
- reps: int or sequence of ints, repetitions along each axis
Returns:
- ndarray: Tiled array
"""Advanced indexing, selection, and data extraction operations.
def take(a, indices, axis=None, out=None, mode='raise'):
"""
Take elements from array along axis.
Parameters:
- a: array_like, source array
- indices: array_like, indices of values to extract
- axis: int, optional, axis over which to select
- out: ndarray, optional, output array
- mode: {'raise', 'wrap', 'clip'}, how to handle out-of-bounds indices
Returns:
- ndarray: Selected elements
"""
def choose(a, choices, out=None, mode='raise'):
"""
Construct array from index array and choice arrays.
Parameters:
- a: int array, index array
- choices: sequence of arrays, choice arrays
- out: array, optional, output array
- mode: {'raise', 'wrap', 'clip'}, how to handle out-of-bounds indices
Returns:
- ndarray: Selected elements
"""
def compress(condition, a, axis=None, out=None):
"""
Return selected slices of array along axis.
Parameters:
- condition: 1D array of bools, selection condition
- a: array_like, input array
- axis: int, optional, axis along which to select
- out: ndarray, optional, output array
Returns:
- ndarray: Compressed array
"""
def extract(condition, arr):
"""
Return elements that satisfy condition.
Parameters:
- condition: array_like, condition array
- arr: array_like, input array
Returns:
- ndarray: Selected elements
"""import cupy as cp
# Create basic arrays
zeros_array = cp.zeros((3, 4))
ones_array = cp.ones((2, 3), dtype=cp.float32)
identity = cp.eye(4)
# Create from ranges
sequence = cp.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linear = cp.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]
# Convert from CPU data
import numpy as np
cpu_data = np.array([[1, 2], [3, 4]])
gpu_data = cp.asarray(cpu_data)import cupy as cp
# Create and reshape arrays
arr = cp.arange(12)
reshaped = arr.reshape(3, 4)
flattened = reshaped.ravel()
# Transpose and move axes
transposed = reshaped.T
moved = cp.moveaxis(reshaped, 0, 1)
# Add/remove dimensions
expanded = cp.expand_dims(arr, axis=1)
squeezed = cp.squeeze(expanded)import cupy as cp
# Create arrays to join
a = cp.array([1, 2, 3])
b = cp.array([4, 5, 6])
# Join arrays
concatenated = cp.concatenate([a, b])
stacked = cp.stack([a, b], axis=0)
vstacked = cp.vstack([a, b])
# Split arrays
arr = cp.arange(9)
split_arrays = cp.split(arr, 3) # Split into 3 equal partsInstall with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda111