CuPy: NumPy & SciPy for GPU (CUDA 10.1 version)
—
Core array creation functions that mirror NumPy's array creation API while creating arrays on GPU memory. These functions form the foundation of CuPy's array operations and provide seamless migration from NumPy code.
Create arrays with specified shapes, data types, and initial values. These functions allocate GPU memory and initialize arrays with the requested data.
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""
Create an array from data on GPU.
Parameters:
- obj: array-like, input data
- dtype: data type, optional
- copy: bool, whether to copy data
- order: memory layout ('C', 'F', 'A', 'K')
- subok: bool, allow subclasses
- ndmin: int, minimum dimensions
Returns:
cupy.ndarray: Array on GPU
"""
def asarray(a, dtype=None, order=None):
"""
Convert input to array.
Parameters:
- a: array-like, input data
- dtype: data type, optional
- order: memory layout, optional
Returns:
cupy.ndarray: Array on GPU
"""
def ascontiguousarray(a, dtype=None):
"""
Return C-contiguous array.
Parameters:
- a: array-like, input data
- dtype: data type, optional
Returns:
cupy.ndarray: C-contiguous array on GPU
"""
def copy(a, order='K'):
"""
Return copy of array.
Parameters:
- a: array-like, input data
- order: memory layout ('C', 'F', 'A', 'K')
Returns:
cupy.ndarray: Copy of array on GPU
"""Create arrays filled with constant values including zeros, ones, and custom fill values.
def zeros(shape, dtype=float, order='C'):
"""
Create array filled with zeros.
Parameters:
- shape: int or tuple, array shape
- dtype: data type, default float
- order: memory layout ('C', 'F')
Returns:
cupy.ndarray: Zero-filled array on GPU
"""
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
"""
Create zeros array with same shape and type.
Parameters:
- a: array-like, reference array
- dtype: data type, optional override
- order: memory layout, optional
- subok: bool, allow subclasses
- shape: tuple, optional shape override
Returns:
cupy.ndarray: Zero-filled array on GPU
"""
def ones(shape, dtype=None, order='C'):
"""
Create array filled with ones.
Parameters:
- shape: int or tuple, array shape
- dtype: data type, default float
- order: memory layout ('C', 'F')
Returns:
cupy.ndarray: One-filled array on GPU
"""
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
"""
Create ones array with same shape and type.
Parameters:
- a: array-like, reference array
- dtype: data type, optional override
- order: memory layout, optional
- subok: bool, allow subclasses
- shape: tuple, optional shape override
Returns:
cupy.ndarray: One-filled array on GPU
"""
def full(shape, fill_value, dtype=None, order='C'):
"""
Create array filled with specified value.
Parameters:
- shape: int or tuple, array shape
- fill_value: scalar, fill value
- dtype: data type, optional
- order: memory layout ('C', 'F')
Returns:
cupy.ndarray: Filled array on GPU
"""
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
"""
Create filled array with same shape and type.
Parameters:
- a: array-like, reference array
- fill_value: scalar, fill value
- dtype: data type, optional override
- order: memory layout, optional
- subok: bool, allow subclasses
- shape: tuple, optional shape override
Returns:
cupy.ndarray: Filled array on GPU
"""
def empty(shape, dtype=float, order='C'):
"""
Create uninitialized array.
Parameters:
- shape: int or tuple, array shape
- dtype: data type, default float
- order: memory layout ('C', 'F')
Returns:
cupy.ndarray: Uninitialized array on GPU
"""
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
"""
Create uninitialized array with same shape and type.
Parameters:
- a: array-like, reference array
- dtype: data type, optional override
- order: memory layout, optional
- subok: bool, allow subclasses
- shape: tuple, optional shape override
Returns:
cupy.ndarray: Uninitialized array on GPU
"""Create arrays with evenly spaced values, linear sequences, and logarithmic sequences.
def arange(start, stop=None, step=None, dtype=None):
"""
Create array with evenly spaced values.
Parameters:
- start: scalar, start value (or stop if single argument)
- stop: scalar, stop value, optional
- step: scalar, step size, optional
- dtype: data type, optional
Returns:
cupy.ndarray: Array with evenly spaced values on GPU
"""
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
"""
Create array with linearly spaced values.
Parameters:
- start: scalar, start value
- stop: scalar, stop value
- num: int, number of samples
- endpoint: bool, include endpoint
- retstep: bool, return step size
- dtype: data type, optional
- axis: int, axis for multi-dimensional start/stop
Returns:
cupy.ndarray or tuple: Linearly spaced array on GPU, optionally with step size
"""
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
"""
Create array with logarithmically spaced values.
Parameters:
- start: scalar, start exponent
- stop: scalar, stop exponent
- num: int, number of samples
- endpoint: bool, include endpoint
- base: scalar, logarithm base
- dtype: data type, optional
- axis: int, axis for multi-dimensional start/stop
Returns:
cupy.ndarray: Logarithmically spaced array on GPU
"""
def meshgrid(*xi, indexing='xy', sparse=False, copy=True):
"""
Create coordinate matrices from coordinate vectors.
Parameters:
- xi: array-like, coordinate vectors
- indexing: str, indexing mode ('xy' or 'ij')
- sparse: bool, return sparse grid
- copy: bool, copy input arrays
Returns:
list of cupy.ndarray: Coordinate matrices on GPU
"""Create special matrices including identity matrices, diagonal matrices, and triangular matrices.
def eye(N, M=None, k=0, dtype=float, order='C'):
"""
Create 2D identity array.
Parameters:
- N: int, number of rows
- M: int, number of columns, optional
- k: int, diagonal offset
- dtype: data type, default float
- order: memory layout ('C', 'F')
Returns:
cupy.ndarray: Identity array on GPU
"""
def identity(n, dtype=None):
"""
Create identity matrix.
Parameters:
- n: int, size of matrix
- dtype: data type, optional
Returns:
cupy.ndarray: Identity matrix on GPU
"""
def diag(v, k=0):
"""
Extract diagonal or create diagonal matrix.
Parameters:
- v: array-like, diagonal values or input array
- k: int, diagonal offset
Returns:
cupy.ndarray: Diagonal array on GPU
"""
def diagflat(v, k=0):
"""
Create 2D array with flattened input as diagonal.
Parameters:
- v: array-like, diagonal values
- k: int, diagonal offset
Returns:
cupy.ndarray: 2D diagonal array on GPU
"""
def tri(N, M=None, k=0, dtype=float):
"""
Create array with ones at and below diagonal.
Parameters:
- N: int, number of rows
- M: int, number of columns, optional
- k: int, diagonal offset
- dtype: data type, default float
Returns:
cupy.ndarray: Lower triangular array on GPU
"""
def tril(m, k=0):
"""
Lower triangle of array.
Parameters:
- m: array-like, input array
- k: int, diagonal offset
Returns:
cupy.ndarray: Lower triangular array on GPU
"""
def triu(m, k=0):
"""
Upper triangle of array.
Parameters:
- m: array-like, input array
- k: int, diagonal offset
Returns:
cupy.ndarray: Upper triangular array on GPU
"""Functions for reshaping, transposing, and rearranging arrays while maintaining data in GPU memory.
def reshape(a, newshape, order='C'):
"""
Change array shape.
Parameters:
- a: array-like, input array
- newshape: int or tuple, new shape
- order: memory layout ('C', 'F', 'A')
Returns:
cupy.ndarray: Reshaped array on GPU
"""
def ravel(a, order='C'):
"""
Return flattened array.
Parameters:
- a: array-like, input array
- order: memory layout ('C', 'F', 'A', 'K')
Returns:
cupy.ndarray: Flattened array on GPU
"""
def transpose(a, axes=None):
"""
Reverse or permute axes.
Parameters:
- a: array-like, input array
- axes: tuple, permutation of axes, optional
Returns:
cupy.ndarray: Transposed array on GPU
"""
def squeeze(a, axis=None):
"""
Remove single-dimensional entries.
Parameters:
- a: array-like, input array
- axis: int or tuple, axes to squeeze, optional
Returns:
cupy.ndarray: Squeezed array on GPU
"""
def expand_dims(a, axis):
"""
Expand array dimensions.
Parameters:
- a: array-like, input array
- axis: int or tuple, position of new axes
Returns:
cupy.ndarray: Array with expanded dimensions on GPU
"""Functions for combining multiple arrays and splitting arrays into sub-arrays.
def concatenate(arrays, axis=0, out=None, dtype=None):
"""
Join arrays along existing axis.
Parameters:
- arrays: sequence of arrays, input arrays
- axis: int, concatenation axis
- out: array, output array, optional
- dtype: data type, optional
Returns:
cupy.ndarray: Concatenated array on GPU
"""
def stack(arrays, axis=0, out=None):
"""
Join arrays along new axis.
Parameters:
- arrays: sequence of arrays, input arrays
- axis: int, stacking axis
- out: array, output array, optional
Returns:
cupy.ndarray: Stacked array on GPU
"""
def vstack(tup):
"""
Stack arrays vertically.
Parameters:
- tup: sequence of arrays, input arrays
Returns:
cupy.ndarray: Vertically stacked array on GPU
"""
def hstack(tup):
"""
Stack arrays horizontally.
Parameters:
- tup: sequence of arrays, input arrays
Returns:
cupy.ndarray: Horizontally stacked array on GPU
"""
def split(ary, indices_or_sections, axis=0):
"""
Split array into sub-arrays.
Parameters:
- ary: array-like, input array
- indices_or_sections: int or array, split points
- axis: int, splitting axis
Returns:
list of cupy.ndarray: Sub-arrays on GPU
"""import cupy as cp
import numpy as np
# Create arrays on GPU
gpu_zeros = cp.zeros((3, 4), dtype=cp.float32)
gpu_ones = cp.ones_like(gpu_zeros)
gpu_range = cp.arange(12).reshape(3, 4)
# Convert between CPU and GPU
cpu_array = np.array([[1, 2], [3, 4]])
gpu_array = cp.asarray(cpu_array) # CPU to GPU
back_to_cpu = cp.asnumpy(gpu_array) # GPU to CPU
# Create sequences
linear = cp.linspace(0, 10, 100)
log_scale = cp.logspace(0, 3, 50) # 10^0 to 10^3# Create special matrices
identity = cp.eye(5)
diagonal = cp.diag([1, 2, 3, 4, 5])
upper_tri = cp.triu(cp.ones((4, 4)))
# Coordinate grids for plotting
x = cp.linspace(-5, 5, 100)
y = cp.linspace(-3, 3, 60)
X, Y = cp.meshgrid(x, y)
Z = cp.sin(cp.sqrt(X**2 + Y**2))Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda101@9.6.1