0
# Array Operations
1
2
Comprehensive array creation functions and manipulation operations compatible with NumPy, enabling easy migration of existing code to GPU acceleration. CuPy provides complete GPU implementations of NumPy's array creation and manipulation capabilities.
3
4
## Capabilities
5
6
### Array Creation
7
8
Create arrays on GPU with various initialization patterns and data sources.
9
10
```python { .api }
11
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
12
"""Create an array from object on GPU.
13
14
Args:
15
object: Array-like object to convert
16
dtype: Data type, defaults to object's dtype
17
copy: Whether to copy data if already an array
18
order: Memory layout ('C', 'F', 'A', 'K')
19
subok: Allow subclasses
20
ndmin: Minimum number of dimensions
21
22
Returns:
23
cupy.ndarray: GPU array
24
"""
25
26
def zeros(shape, dtype=float32, order='C'):
27
"""Create array filled with zeros.
28
29
Args:
30
shape: Shape of the array
31
dtype: Data type, defaults to float32
32
order: Memory layout ('C' or 'F')
33
34
Returns:
35
cupy.ndarray: Zero-filled array
36
"""
37
38
def ones(shape, dtype=None, order='C'):
39
"""Create array filled with ones.
40
41
Args:
42
shape: Shape of the array
43
dtype: Data type, defaults to float64
44
order: Memory layout ('C' or 'F')
45
46
Returns:
47
cupy.ndarray: One-filled array
48
"""
49
50
def empty(shape, dtype=float32, order='C'):
51
"""Create uninitialized array.
52
53
Args:
54
shape: Shape of the array
55
dtype: Data type, defaults to float32
56
order: Memory layout ('C' or 'F')
57
58
Returns:
59
cupy.ndarray: Uninitialized array
60
"""
61
62
def full(shape, fill_value, dtype=None, order='C'):
63
"""Create array filled with specific value.
64
65
Args:
66
shape: Shape of the array
67
fill_value: Value to fill array with
68
dtype: Data type, defaults to fill_value's dtype
69
order: Memory layout ('C' or 'F')
70
71
Returns:
72
cupy.ndarray: Filled array
73
"""
74
75
def arange(start, stop=None, step=1, dtype=None):
76
"""Create array with evenly spaced values.
77
78
Args:
79
start: Start value or stop if single argument
80
stop: Stop value (exclusive)
81
step: Step size
82
dtype: Data type
83
84
Returns:
85
cupy.ndarray: Array with evenly spaced values
86
"""
87
88
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
89
"""Create array with linearly spaced values.
90
91
Args:
92
start: Start value
93
stop: Stop value
94
num: Number of samples
95
endpoint: Include stop value
96
retstep: Return step size
97
dtype: Data type
98
axis: Axis along which to store samples
99
100
Returns:
101
cupy.ndarray or tuple: Array and optionally step size
102
"""
103
104
def eye(N, M=None, k=0, dtype=float, order='C'):
105
"""Create identity matrix or matrix with ones on diagonal.
106
107
Args:
108
N: Number of rows
109
M: Number of columns, defaults to N
110
k: Diagonal offset
111
dtype: Data type
112
order: Memory layout
113
114
Returns:
115
cupy.ndarray: 2D array with ones on k-th diagonal
116
"""
117
118
def identity(n, dtype=None):
119
"""Create identity matrix.
120
121
Args:
122
n: Number of rows and columns
123
dtype: Data type, defaults to float64
124
125
Returns:
126
cupy.ndarray: n x n identity matrix
127
"""
128
```
129
130
### Array-like Creation
131
132
Create arrays similar to existing arrays with different properties.
133
134
```python { .api }
135
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
136
"""Create zeros array with same shape as input."""
137
138
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
139
"""Create ones array with same shape as input."""
140
141
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
142
"""Create uninitialized array with same shape as input."""
143
144
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
145
"""Create filled array with same shape as input."""
146
```
147
148
### Shape Manipulation
149
150
Modify array shapes and dimensions while preserving data.
151
152
```python { .api }
153
def reshape(a, newshape, order='C'):
154
"""Change array shape without changing data.
155
156
Args:
157
a: Input array
158
newshape: New shape
159
order: Memory layout
160
161
Returns:
162
cupy.ndarray: Reshaped array view or copy
163
"""
164
165
def transpose(a, axes=None):
166
"""Reverse or permute array dimensions.
167
168
Args:
169
a: Input array
170
axes: Permutation of axes
171
172
Returns:
173
cupy.ndarray: Transposed array
174
"""
175
176
def flatten(a, order='C'):
177
"""Return flattened copy of array.
178
179
Args:
180
a: Input array
181
order: Memory layout ('C', 'F', 'A', 'K')
182
183
Returns:
184
cupy.ndarray: 1D copy of input
185
"""
186
187
def ravel(a, order='C'):
188
"""Return flattened array (view if possible).
189
190
Args:
191
a: Input array
192
order: Memory layout
193
194
Returns:
195
cupy.ndarray: 1D array (view or copy)
196
"""
197
198
def squeeze(a, axis=None):
199
"""Remove single-dimensional entries.
200
201
Args:
202
a: Input array
203
axis: Specific axes to squeeze
204
205
Returns:
206
cupy.ndarray: Squeezed array
207
"""
208
209
def expand_dims(a, axis):
210
"""Expand array dimensions.
211
212
Args:
213
a: Input array
214
axis: Position of new axis
215
216
Returns:
217
cupy.ndarray: Array with expanded dimensions
218
"""
219
```
220
221
### Array Joining and Splitting
222
223
Combine or split arrays along various axes.
224
225
```python { .api }
226
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
227
"""Join arrays along existing axis.
228
229
Args:
230
arrays: Sequence of arrays
231
axis: Axis to join along
232
out: Output array
233
dtype: Output data type
234
casting: Type casting rule
235
236
Returns:
237
cupy.ndarray: Concatenated array
238
"""
239
240
def stack(arrays, axis=0, out=None):
241
"""Join arrays along new axis.
242
243
Args:
244
arrays: Sequence of arrays
245
axis: Axis to stack along
246
out: Output array
247
248
Returns:
249
cupy.ndarray: Stacked array
250
"""
251
252
def hstack(tup):
253
"""Stack arrays horizontally (column-wise)."""
254
255
def vstack(tup):
256
"""Stack arrays vertically (row-wise)."""
257
258
def dstack(tup):
259
"""Stack arrays depth-wise (along third axis)."""
260
261
def split(ary, indices_or_sections, axis=0):
262
"""Split array into sub-arrays.
263
264
Args:
265
ary: Input array
266
indices_or_sections: Split points or number of sections
267
axis: Axis to split along
268
269
Returns:
270
list: List of sub-arrays
271
"""
272
273
def hsplit(ary, indices_or_sections):
274
"""Split array horizontally."""
275
276
def vsplit(ary, indices_or_sections):
277
"""Split array vertically."""
278
279
def dsplit(ary, indices_or_sections):
280
"""Split array depth-wise."""
281
```
282
283
### Array Copying and Views
284
285
Control memory layout and data sharing between arrays.
286
287
```python { .api }
288
def copy(a, order='K', subok=False):
289
"""Return array copy.
290
291
Args:
292
a: Input array
293
order: Memory layout
294
subok: Allow subclasses
295
296
Returns:
297
cupy.ndarray: Copy of input array
298
"""
299
300
def asarray(a, dtype=None, order=None):
301
"""Convert input to array (copy if needed).
302
303
Args:
304
a: Input data
305
dtype: Data type
306
order: Memory layout
307
308
Returns:
309
cupy.ndarray: Array representation
310
"""
311
312
def ascontiguousarray(a, dtype=None):
313
"""Return C-contiguous array.
314
315
Args:
316
a: Input array
317
dtype: Data type
318
319
Returns:
320
cupy.ndarray: C-contiguous array
321
"""
322
323
def copyto(dst, src, casting='same_kind', where=True):
324
"""Copy values from one array to another.
325
326
Args:
327
dst: Destination array
328
src: Source array or scalar
329
casting: Type casting rule
330
where: Boolean mask
331
"""
332
```
333
334
## Usage Examples
335
336
### Basic Array Creation
337
338
```python
339
import cupy as cp
340
341
# Create various array types
342
zeros_arr = cp.zeros((3, 4))
343
ones_arr = cp.ones((2, 3), dtype=cp.float32)
344
range_arr = cp.arange(0, 10, 2)
345
linear_arr = cp.linspace(0, 1, 5)
346
347
# Create from Python data
348
data = [[1, 2, 3], [4, 5, 6]]
349
gpu_arr = cp.array(data, dtype=cp.float32)
350
```
351
352
### Shape Manipulation
353
354
```python
355
# Original array
356
arr = cp.arange(12) # [0, 1, 2, ..., 11]
357
358
# Reshape operations
359
reshaped = arr.reshape(3, 4)
360
transposed = reshaped.T
361
flattened = reshaped.flatten()
362
363
# Dimension manipulation
364
expanded = cp.expand_dims(arr, axis=1) # Add new axis
365
squeezed = cp.squeeze(expanded) # Remove single dimensions
366
```
367
368
### Array Concatenation
369
370
```python
371
a = cp.array([[1, 2], [3, 4]])
372
b = cp.array([[5, 6], [7, 8]])
373
374
# Join along different axes
375
horizontal = cp.hstack([a, b]) # [[1, 2, 5, 6], [3, 4, 7, 8]]
376
vertical = cp.vstack([a, b]) # [[1, 2], [3, 4], [5, 6], [7, 8]]
377
stacked = cp.stack([a, b], axis=2) # 3D array
378
379
# Split arrays
380
sub_arrays = cp.split(vertical, 2, axis=0) # Split into 2 parts
381
```
382
383
### Memory Management
384
385
```python
386
# Control memory layout and copying
387
cpu_data = [[1, 2, 3], [4, 5, 6]]
388
gpu_arr = cp.asarray(cpu_data) # Minimal copying
389
390
# Ensure C-contiguous layout for performance
391
contiguous = cp.ascontiguousarray(gpu_arr)
392
393
# Explicit copying
394
arr_copy = cp.copy(gpu_arr)
395
```