跳到内容

DOK

基类:SparseArray, NDArrayOperatorsMixin

用于构建稀疏多维数组的类。

参数

名称 类型 描述 默认值
shape tuple[int](ndim)

数组的形状。

必需
数据 dict

此数组中数据的键值对。

None
dtype dtype

此数组的数据类型。如果留空,则从第一个元素推断。

None
fill_value 标量

此数组的填充值。

None

属性

名称 类型 描述
dtype dtype

此数组的数据类型。如果尚未设置任何元素,则可以为 None

shape tuple[int]

此数组的形状。

数据 dict

此字典的键包含所有索引,值包含非零条目。

另请参阅

sparse.COO:一个只读稀疏数组。

示例

您可以从Numpy数组创建sparse.DOK对象。

>>> x = np.eye(5, dtype=np.uint8)
>>> x[2, 3] = 5
>>> s = DOK.from_numpy(x)
>>> s
<DOK: shape=(5, 5), dtype=uint8, nnz=6, fill_value=0>

您也可以仅通过形状创建它们,并使用切片赋值。

>>> s2 = DOK((5, 5), dtype=np.int64)
>>> s2[1:3, 1:3] = [[4, 5], [6, 7]]
>>> s2
<DOK: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>

您可以将sparse.DOK数组转换为sparse.COO数组,或numpy.ndarray对象。

>>> from sparse import COO
>>> s3 = COO(s2)
>>> s3
<COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
>>> s2.todense()
array([[0, 0, 0, 0, 0],
       [0, 4, 5, 0, 0],
       [0, 6, 7, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> s4 = COO.from_numpy(np.eye(4, dtype=np.uint8))
>>> s4
<COO: shape=(4, 4), dtype=uint8, nnz=4, fill_value=0>
>>> s5 = DOK.from_coo(s4)
>>> s5
<DOK: shape=(4, 4), dtype=uint8, nnz=4, fill_value=0>

您也可以从形状和值字典创建sparse.DOK数组。零值将自动忽略。

>>> values = {
...     (1, 2, 3): 4,
...     (3, 2, 1): 0,
... }
>>> s6 = DOK((5, 5, 5), values)
>>> s6
<DOK: shape=(5, 5, 5), dtype=int64, nnz=1, fill_value=0.0>
源代码位于 sparse/numba_backend/_dok.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
class DOK(SparseArray, NDArrayOperatorsMixin):
    """
    A class for building sparse multidimensional arrays.

    Parameters
    ----------
    shape : tuple[int] (DOK.ndim,)
        The shape of the array.
    data : dict, optional
        The key-value pairs for the data in this array.
    dtype : np.dtype, optional
        The data type of this array. If left empty, it is inferred from
        the first element.
    fill_value : scalar, optional
        The fill value of this array.

    Attributes
    ----------
    dtype : numpy.dtype
        The datatype of this array. Can be `None` if no elements
        have been set yet.
    shape : tuple[int]
        The shape of this array.
    data : dict
        The keys of this dictionary contain all the indices and the values
        contain the nonzero entries.

    See Also
    --------
    [`sparse.COO`][] : A read-only sparse array.

    Examples
    --------
    You can create [`sparse.DOK`][] objects from Numpy arrays.

    >>> x = np.eye(5, dtype=np.uint8)
    >>> x[2, 3] = 5
    >>> s = DOK.from_numpy(x)
    >>> s
    <DOK: shape=(5, 5), dtype=uint8, nnz=6, fill_value=0>

    You can also create them from just shapes, and use slicing assignment.

    >>> s2 = DOK((5, 5), dtype=np.int64)
    >>> s2[1:3, 1:3] = [[4, 5], [6, 7]]
    >>> s2
    <DOK: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>

    You can convert [`sparse.DOK`][] arrays to [`sparse.COO`][] arrays, or [`numpy.ndarray`][]
    objects.

    >>> from sparse import COO
    >>> s3 = COO(s2)
    >>> s3
    <COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
    >>> s2.todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[0, 0, 0, 0, 0],
           [0, 4, 5, 0, 0],
           [0, 6, 7, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]])

    >>> s4 = COO.from_numpy(np.eye(4, dtype=np.uint8))
    >>> s4
    <COO: shape=(4, 4), dtype=uint8, nnz=4, fill_value=0>
    >>> s5 = DOK.from_coo(s4)
    >>> s5
    <DOK: shape=(4, 4), dtype=uint8, nnz=4, fill_value=0>

    You can also create [`sparse.DOK`][] arrays from a shape and a dict of
    values. Zeros are automatically ignored.

    >>> values = {
    ...     (1, 2, 3): 4,
    ...     (3, 2, 1): 0,
    ... }
    >>> s6 = DOK((5, 5, 5), values)
    >>> s6
    <DOK: shape=(5, 5, 5), dtype=int64, nnz=1, fill_value=0.0>
    """

    def __init__(self, shape, data=None, dtype=None, fill_value=None):
        from ._common import _is_scipy_sparse_obj
        from ._coo import COO

        self.data = {}

        if isinstance(shape, COO):
            ar = DOK.from_coo(shape)
            self._make_shallow_copy_of(ar)
            return

        if isinstance(shape, np.ndarray):
            ar = DOK.from_numpy(shape)
            self._make_shallow_copy_of(ar)
            return

        if _is_scipy_sparse_obj(shape):
            ar = DOK.from_scipy_sparse(shape)
            self._make_shallow_copy_of(ar)
            return

        self.dtype = np.dtype(dtype)

        if not data:
            data = {}

        super().__init__(shape, fill_value=fill_value)

        if isinstance(data, dict):
            if not dtype:
                if not len(data):
                    self.dtype = np.dtype("float64")
                else:
                    self.dtype = np.result_type(*(np.asarray(x).dtype for x in data.values()))

            for c, d in data.items():
                self[c] = d
        else:
            raise ValueError("data must be a dict.")

    @classmethod
    def from_scipy_sparse(cls, x, /, *, fill_value=None):
        """
        Create a [`sparse.DOK`][] array from a [`scipy.sparse.spmatrix`][].

        Parameters
        ----------
        x : scipy.sparse.spmatrix
            The matrix to convert.
        fill_value : scalar
            The fill-value to use when converting.

        Returns
        -------
        DOK
            The equivalent [`sparse.DOK`][] array.

        Examples
        --------
        >>> import scipy.sparse
        >>> x = scipy.sparse.rand(6, 3, density=0.2)
        >>> s = DOK.from_scipy_sparse(x)
        >>> np.array_equal(x.todense(), s.todense())
        True
        """
        from sparse import COO

        return COO.from_scipy_sparse(x, fill_value=fill_value).asformat(cls)

    @classmethod
    def from_coo(cls, x):
        """
        Get a [`sparse.DOK`][] array from a [`sparse.COO`][] array.

        Parameters
        ----------
        x : COO
            The array to convert.

        Returns
        -------
        DOK
            The equivalent [`sparse.DOK`][] array.

        Examples
        --------
        >>> from sparse import COO
        >>> s = COO.from_numpy(np.eye(4))
        >>> s2 = DOK.from_coo(s)
        >>> s2
        <DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
        """
        ar = cls(x.shape, dtype=x.dtype, fill_value=x.fill_value)

        for c, d in zip(x.coords.T, x.data, strict=True):
            ar.data[tuple(c)] = d

        return ar

    def to_coo(self):
        """
        Convert this [`sparse.DOK`][] array to a [`sparse.COO`][] array.

        Returns
        -------
        COO
            The equivalent [`sparse.COO`][] array.

        Examples
        --------
        >>> s = DOK((5, 5))
        >>> s[1:3, 1:3] = [[4, 5], [6, 7]]
        >>> s
        <DOK: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
        >>> s2 = s.to_coo()
        >>> s2
        <COO: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
        """
        from ._coo import COO

        return COO(self)

    @classmethod
    def from_numpy(cls, x):
        """
        Get a [`sparse.DOK`][] array from a Numpy array.

        Parameters
        ----------
        x : np.ndarray
            The array to convert.

        Returns
        -------
        DOK
            The equivalent [`sparse.DOK`][] array.

        Examples
        --------
        >>> s = DOK.from_numpy(np.eye(4))
        >>> s
        <DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
        """
        ar = cls(x.shape, dtype=x.dtype)

        coords = np.nonzero(x)
        data = x[coords]

        for c in zip(data, *coords, strict=True):
            d, c = c[0], c[1:]
            ar.data[c] = d

        return ar

    @property
    def nnz(self):
        """
        The number of nonzero elements in this array.

        Returns
        -------
        int
            The number of nonzero elements.

        See Also
        --------
        - [`sparse.COO.nnz`][] : Equivalent [`sparse.COO`][] array property.
        - [`numpy.count_nonzero`][] : A similar Numpy function.
        - [`scipy.sparse.coo_matrix.nnz`][] : The Scipy equivalent property.

        Examples
        --------
        >>> values = {
        ...     (1, 2, 3): 4,
        ...     (3, 2, 1): 0,
        ... }
        >>> s = DOK((5, 5, 5), values)
        >>> s.nnz
        1
        """
        return len(self.data)

    @property
    def format(self):
        """
        The storage format of this array.
        Returns
        -------
        str
            The storage format of this array.
        See Also
        -------
        [`scipy.sparse.dok_matrix.format`][] : The Scipy equivalent property.
        Examples
        -------
        >>> import sparse
        >>> s = sparse.random((5, 5), density=0.2, format="dok")
        >>> s.format
        'dok'
        >>> t = sparse.random((5, 5), density=0.2, format="coo")
        >>> t.format
        'coo'
        """
        return "dok"

    @property
    def nbytes(self):
        """
        The number of bytes taken up by this object. Note that for small arrays,
        this may undercount the number of bytes due to the large constant overhead.

        Returns
        -------
        int
            The approximate bytes of memory taken by this object.

        See Also
        --------
        [`numpy.ndarray.nbytes`][] : The equivalent Numpy property.

        Examples
        --------
        >>> import sparse
        >>> x = sparse.random((100, 100), density=0.1, format="dok")
        >>> x.nbytes
        8000
        """
        return self.nnz * self.dtype.itemsize

    def __getitem__(self, key):
        if not isinstance(key, tuple):
            key = (key,)

        if all(isinstance(k, Iterable) for k in key):
            if len(key) != self.ndim:
                raise NotImplementedError(f"Index sequences for all {self.ndim} array dimensions needed!")
            if not all(len(key[0]) == len(k) for k in key):
                raise IndexError("Unequal length of index sequences!")
            return self._fancy_getitem(key)

        key = normalize_index(key, self.shape)

        ret = self.asformat("coo")[key]
        if isinstance(ret, SparseArray):
            ret = ret.asformat("dok")

        return ret

    def _fancy_getitem(self, key):
        """Subset of fancy indexing, when all dimensions are accessed"""
        new_data = {}
        for i, k in enumerate(zip(*key, strict=True)):
            if k in self.data:
                new_data[i] = self.data[k]
        return DOK(
            shape=(len(key[0])),
            data=new_data,
            dtype=self.dtype,
            fill_value=self.fill_value,
        )

    def __setitem__(self, key, value):
        value = np.asarray(value, dtype=self.dtype)

        # 1D fancy indexing
        if self.ndim == 1 and isinstance(key, Iterable) and all(isinstance(i, int | np.integer) for i in key):
            key = (key,)

        if isinstance(key, tuple) and all(isinstance(k, Iterable) for k in key):
            if len(key) != self.ndim:
                raise NotImplementedError(f"Index sequences for all {self.ndim} array dimensions needed!")
            if not all(len(key[0]) == len(k) for k in key):
                raise IndexError("Unequal length of index sequences!")
            self._fancy_setitem(key, value)
            return

        key = normalize_index(key, self.shape)

        key_list = [int(k) if isinstance(k, Integral) else k for k in key]

        self._setitem(key_list, value)

    def _fancy_setitem(self, idxs, values):
        idxs = tuple(np.asanyarray(idxs) for idxs in idxs)
        if not all(np.issubdtype(k.dtype, np.integer) for k in idxs):
            raise IndexError("Indices must be sequences of integer types!")
        if idxs[0].ndim != 1:
            raise IndexError("Indices are not 1d sequences!")
        if values.ndim == 0:
            values = np.full(idxs[0].size, values, self.dtype)
        elif values.ndim > 1:
            raise ValueError(f"Dimension of values ({values.ndim}) must be 0 or 1!")
        if not idxs[0].shape == values.shape:
            raise ValueError(f"Shape mismatch of indices ({idxs[0].shape}) and values ({values.shape})!")
        fill_value = self.fill_value
        data = self.data
        for idx, value in zip(zip(*idxs, strict=True), values, strict=True):
            if value != fill_value:
                data[idx] = value
            elif idx in data:
                del data[idx]

    def _setitem(self, key_list, value):
        value_missing_dims = len([ind for ind in key_list if isinstance(ind, slice)]) - value.ndim

        if value_missing_dims < 0:
            raise ValueError("setting an array element with a sequence.")

        for i, ind in enumerate(key_list):
            if isinstance(ind, slice):
                step = ind.step if ind.step is not None else 1
                if step > 0:
                    start = ind.start if ind.start is not None else 0
                    start = max(start, 0)
                    stop = ind.stop if ind.stop is not None else self.shape[i]
                    stop = min(stop, self.shape[i])
                    if start > stop:
                        start = stop
                else:
                    start = ind.start or self.shape[i] - 1
                    stop = ind.stop if ind.stop is not None else -1
                    start = min(start, self.shape[i] - 1)
                    stop = max(stop, -1)
                    if start < stop:
                        start = stop

                key_list_temp = key_list[:]
                for v_idx, ki in enumerate(range(start, stop, step)):
                    key_list_temp[i] = ki
                    vi = value if value_missing_dims > 0 else (value[0] if value.shape[0] == 1 else value[v_idx])
                    self._setitem(key_list_temp, vi)

                return
            if not isinstance(ind, Integral):
                raise IndexError("All indices must be slices or integers when setting an item.")

        key = tuple(key_list)
        if not equivalent(value, self.fill_value):
            self.data[key] = value[()]
        elif key in self.data:
            del self.data[key]

    def __str__(self):
        summary = f"<DOK: shape={self.shape!s}, dtype={self.dtype!s}, nnz={self.nnz:d}, fill_value={self.fill_value!s}>"
        return self._str_impl(summary)

    __repr__ = __str__

    def todense(self):
        """
        Convert this [`sparse.DOK`][] array into a Numpy array.

        Returns
        -------
        numpy.ndarray
            The equivalent dense array.

        See Also
        --------
        - [`sparse.COO.todense`][] : Equivalent `COO` array method.
        - [`scipy.sparse.coo_matrix.todense`][] : Equivalent Scipy method.

        Examples
        --------
        >>> s = DOK((5, 5))
        >>> s[1:3, 1:3] = [[4, 5], [6, 7]]
        >>> s.todense()  # doctest: +SKIP
        array([[0., 0., 0., 0., 0.],
               [0., 4., 5., 0., 0.],
               [0., 6., 7., 0., 0.],
               [0., 0., 0., 0., 0.],
               [0., 0., 0., 0., 0.]])
        """
        result = np.full(self.shape, self.fill_value, self.dtype)

        for c, d in self.data.items():
            result[c] = d

        return result

    def asformat(self, format, **kwargs):
        """
        Convert this sparse array to a given format.

        Parameters
        ----------
        format : str
            A format string.

        Returns
        -------
        out : SparseArray
            The converted array.

        Raises
        ------
        NotImplementedError
            If the format isn't supported.
        """
        from ._utils import convert_format

        format = convert_format(format)

        if format == "dok":
            return self

        if format == "coo":
            from ._coo import COO

            if len(kwargs) != 0:
                raise ValueError(f"Extra kwargs found: {kwargs}")
            return COO.from_iter(
                self.data,
                shape=self.shape,
                fill_value=self.fill_value,
                dtype=self.dtype,
            )

        return self.asformat("coo").asformat(format, **kwargs)

    def reshape(self, shape, order="C"):
        """
        Returns a new [`sparse.DOK`][] array that is a reshaped version of this array.

        Parameters
        ----------
        shape : tuple[int]
            The desired shape of the output array.

        Returns
        -------
        DOK
            The reshaped output array.

        See Also
        --------
        [`numpy.ndarray.reshape`][] : The equivalent Numpy function.

        Notes
        -----
        The `order` parameter is provided just for compatibility with
        Numpy and isn't actually supported.

        Examples
        --------
        >>> s = DOK.from_numpy(np.arange(25))
        >>> s2 = s.reshape((5, 5))
        >>> s2.todense()  # doctest: +NORMALIZE_WHITESPACE
        array([[ 0,  1,  2,  3,  4],
               [ 5,  6,  7,  8,  9],
               [10, 11, 12, 13, 14],
               [15, 16, 17, 18, 19],
               [20, 21, 22, 23, 24]])
        """
        if order not in {"C", None}:
            raise NotImplementedError("The 'order' parameter is not supported")

        return DOK.from_coo(self.to_coo().reshape(shape))

属性

shape = tuple(int(sh) for sh in shape) 实例属性

fill_value = self.dtype.type(fill_value) 实例属性

device 属性

ndim 属性

此数组的维度数。

返回值

类型 描述
int

此数组的维度数。

另请参阅

示例

>>> from sparse import COO
>>> import numpy as np
>>> x = np.random.rand(1, 2, 3, 1, 2)
>>> s = COO.from_numpy(x)
>>> s.ndim
5
>>> s.ndim == x.ndim
True

size 属性

此数组中所有元素(包括零)的数量。

返回值

类型 描述
int

元素数量。

另请参阅

numpy.ndarray.size : Numpy 等效属性。

示例

>>> from sparse import COO
>>> import numpy as np
>>> x = np.zeros((10, 10))
>>> s = COO.from_numpy(x)
>>> s.size
100

density 属性

此数组中非零元素与所有元素的比率。

返回值

类型 描述
float

非零元素与所有元素的比率。

另请参阅

示例

>>> import numpy as np
>>> from sparse import COO
>>> x = np.zeros((8, 8))
>>> x[0, :] = 1
>>> s = COO.from_numpy(x)
>>> s.density
0.125

amax = max 类属性 实例属性

amin = min 类属性 实例属性

round_ = round 类属性 实例属性

real 属性

数组的实部。

示例

>>> from sparse import COO
>>> x = COO.from_numpy([1 + 0j, 0 + 1j])
>>> x.real.todense()
array([1., 0.])
>>> x.real.dtype
dtype('float64')

返回值

名称 类型 描述
out SparseArray

数组元素的实部。如果数组 dtype 是实数,则输出使用数组的 dtype。如果数组是复数,则输出 dtype 为浮点数。

另请参阅

imag 属性

数组的虚部。

示例

>>> from sparse import COO
>>> x = COO.from_numpy([1 + 0j, 0 + 1j])
>>> x.imag.todense()
array([0., 1.])
>>> x.imag.dtype
dtype('float64')

返回值

名称 类型 描述
out SparseArray

数组元素的虚部。如果数组 dtype 是实数,则输出使用数组的 dtype。如果数组是复数,则输出 dtype 为浮点数。

另请参阅

data = {} 实例属性

dtype = np.dtype(dtype) 实例属性

nnz 属性

此数组中非零元素的数量。

返回值

类型 描述
int

非零元素的数量。

另请参阅

示例

>>> values = {
...     (1, 2, 3): 4,
...     (3, 2, 1): 0,
... }
>>> s = DOK((5, 5, 5), values)
>>> s.nnz
1

format 属性

此数组的存储格式。

返回值

类型 描述
str

此数组的存储格式。

另请参阅

scipy.sparse.dok_matrix.format : Scipy 等效属性。

示例

>>> import sparse
>>> s = sparse.random((5, 5), density=0.2, format="dok")
>>> s.format
'dok'
>>> t = sparse.random((5, 5), density=0.2, format="coo")
>>> t.format
'coo'

nbytes 属性

此对象占用的字节数。请注意,对于小型数组,由于恒定开销较大,此值可能会低估字节数。

返回值

类型 描述
int

此对象占用的近似内存字节数。

另请参阅

numpy.ndarray.nbytes : 等效的 Numpy 属性。

示例

>>> import sparse
>>> x = sparse.random((100, 100), density=0.1, format="dok")
>>> x.nbytes
8000

函数

to_device(device, /, *, stream=None)

源代码在 sparse/numba_backend/_sparse_array.py
55
56
57
58
59
def to_device(self, device, /, *, stream=None):
    if device != "cpu":
        raise ValueError("Only `device='cpu'` is supported.")

    return self

reduce(method, axis=(0,), keepdims=False, **kwargs)

对此数组执行归约操作。

参数

名称 类型 描述 默认值
method ufunc

用于执行归约的方法。

必需
axis Union[int, Iterable[int]]

执行归约的轴。默认使用所有轴。

(0,)
keepdims bool_

是否保留原始数组的维度。

False
**kwargs dict

传递给归约操作的任何额外参数。

{}
另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def reduce(self, method, axis=(0,), keepdims=False, **kwargs):
    """
    Performs a reduction operation on this array.

    Parameters
    ----------
    method : numpy.ufunc
        The method to use for performing the reduction.
    axis : Union[int, Iterable[int]], optional
        The axes along which to perform the reduction. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    **kwargs : dict
        Any extra arguments to pass to the reduction operation.

    See Also
    --------
    - [`numpy.ufunc.reduce`][] : A similar Numpy method.
    - [`sparse.COO.reduce`][] : This method implemented on COO arrays.
    - [`sparse.GCXS.reduce`][] : This method implemented on GCXS arrays.
    """
    axis = normalize_axis(axis, self.ndim)
    zero_reduce_result = method.reduce([self.fill_value, self.fill_value], **kwargs)
    reduce_super_ufunc = _reduce_super_ufunc.get(method)
    if not equivalent(zero_reduce_result, self.fill_value) and reduce_super_ufunc is None:
        raise ValueError(f"Performing this reduction operation would produce a dense result: {method!s}")

    if not isinstance(axis, tuple):
        axis = (axis,)
    out = self._reduce_calc(method, axis, keepdims, **kwargs)
    if len(out) == 1:
        return out[0]
    data, counts, axis, n_cols, arr_attrs = out
    result_fill_value = self.fill_value
    if reduce_super_ufunc is None:
        missing_counts = counts != n_cols
        data[missing_counts] = method(data[missing_counts], self.fill_value, **kwargs)
    else:
        data = method(
            data,
            reduce_super_ufunc(self.fill_value, n_cols - counts),
        ).astype(data.dtype)
        result_fill_value = reduce_super_ufunc(self.fill_value, n_cols)

    out = self._reduce_return(data, arr_attrs, result_fill_value)

    if keepdims:
        shape = list(self.shape)
        for ax in axis:
            shape[ax] = 1
        out = out.reshape(shape)

    if out.ndim == 0:
        return out[()]

    return out

sum(axis=None, keepdims=False, dtype=None, out=None)

沿给定轴执行求和操作。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

进行求和的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
dtype dtype

输出数组的数据类型。

None

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def sum(self, axis=None, keepdims=False, dtype=None, out=None):
    """
    Performs a sum operation along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to sum. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    dtype : numpy.dtype
        The data type of the output array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    - [`numpy.sum`][] : Equivalent numpy function.
    - [`scipy.sparse.coo_matrix.sum`][] : Equivalent Scipy function.
    """
    return np.add.reduce(self, out=out, axis=axis, keepdims=keepdims, dtype=dtype)

max(axis=None, keepdims=False, out=None)

沿给定轴取最大值。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

取最大值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
out dtype

输出数组的数据类型。

None

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def max(self, axis=None, keepdims=False, out=None):
    """
    Maximize along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to maximize. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    out : numpy.dtype
        The data type of the output array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    - [`numpy.max`][] : Equivalent numpy function.
    - [`scipy.sparse.coo_matrix.max`][] : Equivalent Scipy function.
    """
    return np.maximum.reduce(self, out=out, axis=axis, keepdims=keepdims)

any(axis=None, keepdims=False, out=None)

检查数组中是否有任何值为 True。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

取最小值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅

numpy.any : 等效的 numpy 函数。

源代码在 sparse/numba_backend/_sparse_array.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def any(self, axis=None, keepdims=False, out=None):
    """
    See if any values along array are ``True``. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to minimize. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    [`numpy.any`][] : Equivalent numpy function.
    """
    return np.logical_or.reduce(self, out=out, axis=axis, keepdims=keepdims)

all(axis=None, keepdims=False, out=None)

检查数组中所有值是否都为 True。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

取最小值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅

numpy.all : 等效的 numpy 函数。

源代码在 sparse/numba_backend/_sparse_array.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def all(self, axis=None, keepdims=False, out=None):
    """
    See if all values in an array are ``True``. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to minimize. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    [`numpy.all`][] : Equivalent numpy function.
    """
    return np.logical_and.reduce(self, out=out, axis=axis, keepdims=keepdims)

min(axis=None, keepdims=False, out=None)

沿给定轴取最小值。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

取最小值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
out dtype

输出数组的数据类型。

None

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def min(self, axis=None, keepdims=False, out=None):
    """
    Minimize along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to minimize. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    out : numpy.dtype
        The data type of the output array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    - [`numpy.min`][] : Equivalent numpy function.
    - [`scipy.sparse.coo_matrix.min`][] : Equivalent Scipy function.
    """
    return np.minimum.reduce(self, out=out, axis=axis, keepdims=keepdims)

prod(axis=None, keepdims=False, dtype=None, out=None)

沿给定轴执行乘积操作。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

进行乘法的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
dtype dtype

输出数组的数据类型。

None

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅

numpy.prod : 等效的 numpy 函数。

源代码在 sparse/numba_backend/_sparse_array.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def prod(self, axis=None, keepdims=False, dtype=None, out=None):
    """
    Performs a product operation along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to multiply. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    dtype : numpy.dtype
        The data type of the output array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    [`numpy.prod`][] : Equivalent numpy function.
    """
    return np.multiply.reduce(self, out=out, axis=axis, keepdims=keepdims, dtype=dtype)

round(decimals=0, out=None)

均匀地四舍五入到给定的小数位数。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def round(self, decimals=0, out=None):
    """
    Evenly round to the given number of decimals.

    See Also
    --------
    - [`numpy.round`][] :
        NumPy equivalent ufunc.
    - [`sparse.elemwise`][] :
        Apply an arbitrary element-wise function to one or two
        arguments.
    """
    if out is not None and not isinstance(out, tuple):
        out = (out,)
    return self.__array_ufunc__(np.round, "__call__", self, decimals=decimals, out=out)

clip(min=None, max=None, out=None)

裁剪(限制)数组中的值。

返回一个值限制在 [min, max] 范围内的数组。必须提供 min 或 max 之一。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def clip(self, min=None, max=None, out=None):
    """
    Clip (limit) the values in the array.

    Return an array whose values are limited to ``[min, max]``. One of min
    or max must be given.

    See Also
    --------
    - [sparse.clip][] : For full documentation and more details.
    - [`numpy.clip`][] : Equivalent NumPy function.
    """
    if out is not None and not isinstance(out, tuple):
        out = (out,)
    return self.__array_ufunc__(np.clip, "__call__", self, a_min=min, a_max=max, out=out)

astype(dtype, casting='unsafe', copy=True)

数组的副本,转换为指定类型。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
def astype(self, dtype, casting="unsafe", copy=True):
    """
    Copy of the array, cast to a specified type.

    See Also
    --------
    - [`scipy.sparse.coo_matrix.astype`][] :
        SciPy sparse equivalent function
    - [`numpy.ndarray.astype`][] :
        NumPy equivalent ufunc.
    - [`sparse.elemwise`][] :
        Apply an arbitrary element-wise function to one or two
        arguments.
    """
    # this matches numpy's behavior
    if self.dtype == dtype and not copy:
        return self
    return self.__array_ufunc__(np.ndarray.astype, "__call__", self, dtype=dtype, copy=copy, casting=casting)

mean(axis=None, keepdims=False, dtype=None, out=None)

沿给定轴计算均值。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

计算均值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
dtype dtype

输出数组的数据类型。

None

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅
备注
  • 提供 out 参数仅为了与 Numpy 兼容,实际上并不受支持。

示例

您可以使用 sparse.COO.mean 计算数组沿任意维度的均值。

>>> from sparse import COO
>>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
>>> s = COO.from_numpy(x)
>>> s2 = s.mean(axis=1)
>>> s2.todense()
array([0.5, 1.5, 0., 0.])

您还可以使用 keepdims 参数在计算均值后保留维度。

>>> s3 = s.mean(axis=0, keepdims=True)
>>> s3.shape
(1, 4)

如果需要,可以传入输出数据类型。

>>> s4 = s.mean(axis=0, dtype=np.float16)
>>> s4.dtype
dtype('float16')

默认情况下,这将数组归约为一个数字,计算沿所有轴的均值。

>>> s.mean()
np.float64(0.5)
源代码在 sparse/numba_backend/_sparse_array.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def mean(self, axis=None, keepdims=False, dtype=None, out=None):
    """
    Compute the mean along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to compute the mean. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    dtype : numpy.dtype
        The data type of the output array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    - [`numpy.ndarray.mean`][] : Equivalent numpy method.
    - [`scipy.sparse.coo_matrix.mean`][] : Equivalent Scipy method.

    Notes
    -----
    * The `out` parameter is provided just for compatibility with
      Numpy and isn't actually supported.

    Examples
    --------
    You can use [`sparse.COO.mean`][] to compute the mean of an array across any
    dimension.

    >>> from sparse import COO
    >>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
    >>> s = COO.from_numpy(x)
    >>> s2 = s.mean(axis=1)
    >>> s2.todense()  # doctest: +SKIP
    array([0.5, 1.5, 0., 0.])

    You can also use the `keepdims` argument to keep the dimensions
    after the mean.

    >>> s3 = s.mean(axis=0, keepdims=True)
    >>> s3.shape
    (1, 4)

    You can pass in an output datatype, if needed.

    >>> s4 = s.mean(axis=0, dtype=np.float16)
    >>> s4.dtype
    dtype('float16')

    By default, this reduces the array down to one number, computing the
    mean along all axes.

    >>> s.mean()
    np.float64(0.5)
    """

    if axis is None:
        axis = tuple(range(self.ndim))
    elif not isinstance(axis, tuple):
        axis = (axis,)
    den = reduce(operator.mul, (self.shape[i] for i in axis), 1)

    if dtype is None:
        if issubclass(self.dtype.type, np.integer | np.bool_):
            dtype = inter_dtype = np.dtype("f8")
        else:
            dtype = self.dtype
            inter_dtype = np.dtype("f4") if issubclass(dtype.type, np.float16) else dtype
    else:
        inter_dtype = dtype

    num = self.sum(axis=axis, keepdims=keepdims, dtype=inter_dtype)

    if num.ndim:
        out = np.true_divide(num, den, casting="unsafe")
        return out.astype(dtype) if out.dtype != dtype else out
    return np.divide(num, den, dtype=dtype, out=out)

var(axis=None, dtype=None, out=None, ddof=0, keepdims=False)

沿给定轴计算方差。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

计算方差的轴。默认使用所有轴。

None
dtype dtype

输出数据类型。

None
out SparseArray

写入输出的数组。

None
ddof int

自由度。

0
keepdims bool_

是否保留原始数组的维度。

False

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅

numpy.ndarray.var : 等效的 numpy 方法。

示例

您可以使用 sparse.COO.var 计算数组沿任意维度的方差。

>>> from sparse import COO
>>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
>>> s = COO.from_numpy(x)
>>> s2 = s.var(axis=1)
>>> s2.todense()
array([0.6875, 0.1875])

您还可以使用 keepdims 参数在计算方差后保留维度。

>>> s3 = s.var(axis=0, keepdims=True)
>>> s3.shape
(1, 4)

如果需要,可以传入输出数据类型。

>>> s4 = s.var(axis=0, dtype=np.float16)
>>> s4.dtype
dtype('float16')

默认情况下,这将数组归约为一个数字,计算沿所有轴的方差。

>>> s.var()
np.float64(0.5)
源代码在 sparse/numba_backend/_sparse_array.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
    """
    Compute the variance along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to compute the variance. Uses all axes by default.
    dtype : numpy.dtype, optional
        The output datatype.
    out : SparseArray, optional
        The array to write the output to.
    ddof : int
        The degrees of freedom.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    [`numpy.ndarray.var`][] : Equivalent numpy method.

    Examples
    --------
    You can use [`sparse.COO.var`][] to compute the variance of an array across any
    dimension.

    >>> from sparse import COO
    >>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
    >>> s = COO.from_numpy(x)
    >>> s2 = s.var(axis=1)
    >>> s2.todense()  # doctest: +SKIP
    array([0.6875, 0.1875])

    You can also use the `keepdims` argument to keep the dimensions
    after the variance.

    >>> s3 = s.var(axis=0, keepdims=True)
    >>> s3.shape
    (1, 4)

    You can pass in an output datatype, if needed.

    >>> s4 = s.var(axis=0, dtype=np.float16)
    >>> s4.dtype
    dtype('float16')

    By default, this reduces the array down to one number, computing the
    variance along all axes.

    >>> s.var()
    np.float64(0.5)
    """
    axis = normalize_axis(axis, self.ndim)

    if axis is None:
        axis = tuple(range(self.ndim))

    if not isinstance(axis, tuple):
        axis = (axis,)

    rcount = reduce(operator.mul, (self.shape[a] for a in axis), 1)
    # Make this warning show up on top.
    if ddof >= rcount:
        warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=1)

    # Cast bool, unsigned int, and int to float64 by default
    if dtype is None and issubclass(self.dtype.type, np.integer | np.bool_):
        dtype = np.dtype("f8")

    arrmean = self.sum(axis, dtype=dtype, keepdims=True)[...]
    np.divide(arrmean, rcount, out=arrmean)
    x = self - arrmean
    if issubclass(self.dtype.type, np.complexfloating):
        x = x.real * x.real + x.imag * x.imag
    else:
        x = np.multiply(x, x, out=x)

    ret = x.sum(axis=axis, dtype=dtype, out=out, keepdims=keepdims)

    # Compute degrees of freedom and make sure it is not negative.
    rcount = max([rcount - ddof, 0])

    ret = ret[...]
    np.divide(ret, rcount, out=ret, casting="unsafe")
    return ret[()]

std(axis=None, dtype=None, out=None, ddof=0, keepdims=False)

沿给定轴计算标准差。默认使用所有轴。

参数

名称 类型 描述 默认值
axis Union[int, Iterable[int]]

计算标准差的轴。默认使用所有轴。

None
dtype dtype

输出数据类型。

None
out SparseArray

写入输出的数组。

None
ddof int

自由度。

0
keepdims bool_

是否保留原始数组的维度。

False

返回值

类型 描述
SparseArray

归约后的稀疏输出数组。

另请参阅

numpy.ndarray.std : 等效的 numpy 方法。

示例

您可以使用 sparse.COO.std 计算数组沿任意维度的标准差。

>>> from sparse import COO
>>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
>>> s = COO.from_numpy(x)
>>> s2 = s.std(axis=1)
>>> s2.todense()
array([0.8291562, 0.4330127])

您还可以使用 keepdims 参数在计算标准差后保留维度。

>>> s3 = s.std(axis=0, keepdims=True)
>>> s3.shape
(1, 4)

如果需要,可以传入输出数据类型。

>>> s4 = s.std(axis=0, dtype=np.float16)
>>> s4.dtype
dtype('float16')

默认情况下,这将数组归约为一个数字,计算沿所有轴的标准差。

>>> s.std()
0.7071067811865476
源代码在 sparse/numba_backend/_sparse_array.py
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
    """
    Compute the standard deviation along the given axes. Uses all axes by default.

    Parameters
    ----------
    axis : Union[int, Iterable[int]], optional
        The axes along which to compute the standard deviation. Uses
        all axes by default.
    dtype : numpy.dtype, optional
        The output datatype.
    out : SparseArray, optional
        The array to write the output to.
    ddof : int
        The degrees of freedom.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.

    Returns
    -------
    SparseArray
        The reduced output sparse array.

    See Also
    --------
    [`numpy.ndarray.std`][] : Equivalent numpy method.

    Examples
    --------
    You can use [`sparse.COO.std`][] to compute the standard deviation of an array
    across any dimension.

    >>> from sparse import COO
    >>> x = np.array([[1, 2, 0, 0], [0, 1, 0, 0]], dtype="i8")
    >>> s = COO.from_numpy(x)
    >>> s2 = s.std(axis=1)
    >>> s2.todense()  # doctest: +SKIP
    array([0.8291562, 0.4330127])

    You can also use the `keepdims` argument to keep the dimensions
    after the standard deviation.

    >>> s3 = s.std(axis=0, keepdims=True)
    >>> s3.shape
    (1, 4)

    You can pass in an output datatype, if needed.

    >>> s4 = s.std(axis=0, dtype=np.float16)
    >>> s4.dtype
    dtype('float16')

    By default, this reduces the array down to one number, computing the
    standard deviation along all axes.

    >>> s.std()  # doctest: +SKIP
    0.7071067811865476
    """
    ret = self.var(axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims)

    return np.sqrt(ret)

conj()

按元素返回复共轭。

复数的复共轭是通过改变其虚部的符号获得的。

示例

>>> from sparse import COO
>>> x = COO.from_numpy([1 + 2j, 2 - 1j])
>>> res = x.conj()
>>> res.todense()
array([1.-2.j, 2.+1.j])
>>> res.dtype
dtype('complex128')

返回值

名称 类型 描述
out SparseArray

复共轭,与输入具有相同的 dtype。

另请参阅
源代码在 sparse/numba_backend/_sparse_array.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
def conj(self):
    """Return the complex conjugate, element-wise.

    The complex conjugate of a complex number is obtained by changing the
    sign of its imaginary part.

    Examples
    --------
    >>> from sparse import COO
    >>> x = COO.from_numpy([1 + 2j, 2 - 1j])
    >>> res = x.conj()
    >>> res.todense()  # doctest: +SKIP
    array([1.-2.j, 2.+1.j])
    >>> res.dtype
    dtype('complex128')

    Returns
    -------
    out : SparseArray
        The complex conjugate, with same dtype as the input.

    See Also
    --------
    - [`numpy.ndarray.conj`][] : NumPy equivalent method.
    - [`numpy.conj`][] : NumPy equivalent function.
    """
    return np.conj(self)

isinf() 抽象方法

源代码在 sparse/numba_backend/_sparse_array.py
987
988
989
@abstractmethod
def isinf(self):
    """ """

isnan() 抽象方法

源代码在 sparse/numba_backend/_sparse_array.py
991
992
993
@abstractmethod
def isnan(self):
    """ """

from_scipy_sparse(x, /, *, fill_value=None) 类方法

scipy.sparse.spmatrix创建sparse.DOK数组。

参数

名称 类型 描述 默认值
x spmatrix

要转换的矩阵。

必需
fill_value 标量

转换时使用的填充值。

None

返回值

类型 描述
DOK

等效的sparse.DOK数组。

示例

>>> import scipy.sparse
>>> x = scipy.sparse.rand(6, 3, density=0.2)
>>> s = DOK.from_scipy_sparse(x)
>>> np.array_equal(x.todense(), s.todense())
True
源代码位于 sparse/numba_backend/_dok.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
@classmethod
def from_scipy_sparse(cls, x, /, *, fill_value=None):
    """
    Create a [`sparse.DOK`][] array from a [`scipy.sparse.spmatrix`][].

    Parameters
    ----------
    x : scipy.sparse.spmatrix
        The matrix to convert.
    fill_value : scalar
        The fill-value to use when converting.

    Returns
    -------
    DOK
        The equivalent [`sparse.DOK`][] array.

    Examples
    --------
    >>> import scipy.sparse
    >>> x = scipy.sparse.rand(6, 3, density=0.2)
    >>> s = DOK.from_scipy_sparse(x)
    >>> np.array_equal(x.todense(), s.todense())
    True
    """
    from sparse import COO

    return COO.from_scipy_sparse(x, fill_value=fill_value).asformat(cls)

from_coo(x) 类方法

sparse.COO数组获取sparse.DOK数组。

参数

名称 类型 描述 默认值
x COO

要转换的数组。

必需

返回值

类型 描述
DOK

等效的sparse.DOK数组。

示例

>>> from sparse import COO
>>> s = COO.from_numpy(np.eye(4))
>>> s2 = DOK.from_coo(s)
>>> s2
<DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
源代码位于 sparse/numba_backend/_dok.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@classmethod
def from_coo(cls, x):
    """
    Get a [`sparse.DOK`][] array from a [`sparse.COO`][] array.

    Parameters
    ----------
    x : COO
        The array to convert.

    Returns
    -------
    DOK
        The equivalent [`sparse.DOK`][] array.

    Examples
    --------
    >>> from sparse import COO
    >>> s = COO.from_numpy(np.eye(4))
    >>> s2 = DOK.from_coo(s)
    >>> s2
    <DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
    """
    ar = cls(x.shape, dtype=x.dtype, fill_value=x.fill_value)

    for c, d in zip(x.coords.T, x.data, strict=True):
        ar.data[tuple(c)] = d

    return ar

to_coo()

将此sparse.DOK数组转换为sparse.COO数组。

返回值

类型 描述
COO

等效的sparse.COO数组。

示例

>>> s = DOK((5, 5))
>>> s[1:3, 1:3] = [[4, 5], [6, 7]]
>>> s
<DOK: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
>>> s2 = s.to_coo()
>>> s2
<COO: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
源代码位于 sparse/numba_backend/_dok.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def to_coo(self):
    """
    Convert this [`sparse.DOK`][] array to a [`sparse.COO`][] array.

    Returns
    -------
    COO
        The equivalent [`sparse.COO`][] array.

    Examples
    --------
    >>> s = DOK((5, 5))
    >>> s[1:3, 1:3] = [[4, 5], [6, 7]]
    >>> s
    <DOK: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
    >>> s2 = s.to_coo()
    >>> s2
    <COO: shape=(5, 5), dtype=float64, nnz=4, fill_value=0.0>
    """
    from ._coo import COO

    return COO(self)

from_numpy(x) 类方法

从Numpy数组获取sparse.DOK数组。

参数

名称 类型 描述 默认值
x ndarray

要转换的数组。

必需

返回值

类型 描述
DOK

等效的sparse.DOK数组。

示例

>>> s = DOK.from_numpy(np.eye(4))
>>> s
<DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
源代码位于 sparse/numba_backend/_dok.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
@classmethod
def from_numpy(cls, x):
    """
    Get a [`sparse.DOK`][] array from a Numpy array.

    Parameters
    ----------
    x : np.ndarray
        The array to convert.

    Returns
    -------
    DOK
        The equivalent [`sparse.DOK`][] array.

    Examples
    --------
    >>> s = DOK.from_numpy(np.eye(4))
    >>> s
    <DOK: shape=(4, 4), dtype=float64, nnz=4, fill_value=0.0>
    """
    ar = cls(x.shape, dtype=x.dtype)

    coords = np.nonzero(x)
    data = x[coords]

    for c in zip(data, *coords, strict=True):
        d, c = c[0], c[1:]
        ar.data[c] = d

    return ar

todense()

将此sparse.DOK数组转换为Numpy数组。

返回值

类型 描述
ndarray

等效的密集数组。

另请参阅

示例

>>> s = DOK((5, 5))
>>> s[1:3, 1:3] = [[4, 5], [6, 7]]
>>> s.todense()
array([[0., 0., 0., 0., 0.],
       [0., 4., 5., 0., 0.],
       [0., 6., 7., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
源代码位于 sparse/numba_backend/_dok.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def todense(self):
    """
    Convert this [`sparse.DOK`][] array into a Numpy array.

    Returns
    -------
    numpy.ndarray
        The equivalent dense array.

    See Also
    --------
    - [`sparse.COO.todense`][] : Equivalent `COO` array method.
    - [`scipy.sparse.coo_matrix.todense`][] : Equivalent Scipy method.

    Examples
    --------
    >>> s = DOK((5, 5))
    >>> s[1:3, 1:3] = [[4, 5], [6, 7]]
    >>> s.todense()  # doctest: +SKIP
    array([[0., 0., 0., 0., 0.],
           [0., 4., 5., 0., 0.],
           [0., 6., 7., 0., 0.],
           [0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.]])
    """
    result = np.full(self.shape, self.fill_value, self.dtype)

    for c, d in self.data.items():
        result[c] = d

    return result

asformat(format, **kwargs)

将此稀疏数组转换为给定格式。

参数

名称 类型 描述 默认值
format str

格式字符串。

必需

返回值

名称 类型 描述
out SparseArray

转换后的数组。

引发

类型 描述
NotImplementedError

如果不支持该格式。

源代码位于 sparse/numba_backend/_dok.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def asformat(self, format, **kwargs):
    """
    Convert this sparse array to a given format.

    Parameters
    ----------
    format : str
        A format string.

    Returns
    -------
    out : SparseArray
        The converted array.

    Raises
    ------
    NotImplementedError
        If the format isn't supported.
    """
    from ._utils import convert_format

    format = convert_format(format)

    if format == "dok":
        return self

    if format == "coo":
        from ._coo import COO

        if len(kwargs) != 0:
            raise ValueError(f"Extra kwargs found: {kwargs}")
        return COO.from_iter(
            self.data,
            shape=self.shape,
            fill_value=self.fill_value,
            dtype=self.dtype,
        )

    return self.asformat("coo").asformat(format, **kwargs)

reshape(shape, order='C')

返回一个新的sparse.DOK数组,它是此数组的重塑版本。

参数

名称 类型 描述 默认值
shape tuple[int]

所需输出数组的形状。

必需

返回值

类型 描述
DOK

重塑后的输出数组。

另请参阅

numpy.ndarray.reshape : 等效的 Numpy 函数。

备注

提供 order 参数仅为了与 Numpy 兼容,实际上并不受支持。

示例

>>> s = DOK.from_numpy(np.arange(25))
>>> s2 = s.reshape((5, 5))
>>> s2.todense()
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
源代码位于 sparse/numba_backend/_dok.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def reshape(self, shape, order="C"):
    """
    Returns a new [`sparse.DOK`][] array that is a reshaped version of this array.

    Parameters
    ----------
    shape : tuple[int]
        The desired shape of the output array.

    Returns
    -------
    DOK
        The reshaped output array.

    See Also
    --------
    [`numpy.ndarray.reshape`][] : The equivalent Numpy function.

    Notes
    -----
    The `order` parameter is provided just for compatibility with
    Numpy and isn't actually supported.

    Examples
    --------
    >>> s = DOK.from_numpy(np.arange(25))
    >>> s2 = s.reshape((5, 5))
    >>> s2.todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])
    """
    if order not in {"C", None}:
        raise NotImplementedError("The 'order' parameter is not supported")

    return DOK.from_coo(self.to_coo().reshape(shape))