跳到内容

COO

基类: SparseArray, NDArrayOperatorsMixin

一个稀疏的多维数组。

它以COO格式存储。它依赖于NumPy和Scipy.sparse进行计算,但支持任意维度的数组。

参数

名称 类型 描述 默认值
coords ndarray(ndim, nnz)

一个数组,保存每个值的索引位置。其形状应为(维度数,非零元素数)。

必填
data ndarray(nnz)

一个值数组。如果数据在所有坐标中都相同,也可以提供一个标量。如果未给定,则默认为sparse.as_coo

shape tuple[int](ndim)

数组的形状。

has_duplicates bool_

一个值,指示为sparse.COO.coords提供的值是否包含重复项。请注意,当coords确实包含重复项时,将其设置为False可能会导致未定义的行为。

True
sorted bool_

一个值,指示coords中的值是否已排序。请注意,当sparse.COO.coords未排序时,将其设置为True可能会导致未定义的行为。

False
prune bool_

一个标志,指示是否应修剪data中存在的任何填充值。

False
cache bool_

是否为各种操作启用缓存。请参阅sparse.COO.enable_caching

False
fill_value

此数组的填充值。

属性

名称 类型 描述
coords ndarray(ndim, nnz)

一个数组,保存每个非零元素的坐标。

data ndarray(nnz)

一个数组,保存与sparse.COO.coords对应的值。

shape tuple[int](ndim)

此数组的维度。

另请参阅

示例

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

>>> x = np.eye(4, dtype=np.uint8)
>>> x[2, 3] = 5
>>> s = COO.from_numpy(x)
>>> s
<COO: shape=(4, 4), dtype=uint8, nnz=5, fill_value=0>
>>> s.data
array([1, 1, 1, 5, 1], dtype=uint8)
>>> s.coords
array([[0, 1, 2, 2, 3],
       [0, 1, 2, 3, 3]])

sparse.COO对象支持基本的算术和二进制操作。

>>> x2 = np.eye(4, dtype=np.uint8)
>>> x2[3, 2] = 5
>>> s2 = COO.from_numpy(x2)
>>> (s + s2).todense()
array([[2, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 2, 5],
       [0, 0, 5, 2]], dtype=uint8)
>>> (s * s2).todense()
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]], dtype=uint8)

二进制操作支持广播。

>>> x3 = np.zeros((4, 1), dtype=np.uint8)
>>> x3[2, 0] = 1
>>> s3 = COO.from_numpy(x3)
>>> (s * s3).todense()
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 1, 5],
       [0, 0, 0, 0]], dtype=uint8)

sparse.COO对象也支持点积和归约。

>>> s.dot(s.T).sum(axis=0).todense()
array([ 1,  1, 31,  6], dtype=uint64)

您也可以在sparse.COO数组上使用Numpy的ufunc操作。

>>> np.sum(s, axis=1).todense()
array([1, 1, 6, 1], dtype=uint64)
>>> np.round(np.sqrt(s, dtype=np.float64), decimals=1).todense()
array([[ 1. ,  0. ,  0. ,  0. ],
       [ 0. ,  1. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ,  2.2],
       [ 0. ,  0. ,  0. ,  1. ]])

导致密集数组的操作通常会产生不同的填充值,如下所示。

>>> np.exp(s)
<COO: shape=(4, 4), dtype=float16, nnz=5, fill_value=1.0>

您也可以从坐标和数据创建sparse.COO数组。

>>> coords = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 3], [0, 3, 2, 0, 1]]
>>> data = [1, 2, 3, 4, 5]
>>> s4 = COO(coords, data, shape=(3, 4, 5))
>>> s4
<COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>

如果数据在所有坐标中都相同,您也可以指定一个标量。

>>> coords = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 3], [0, 3, 2, 0, 1]]
>>> data = 1
>>> s5 = COO(coords, data, shape=(3, 4, 5))
>>> s5
<COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>

遵循scipy.sparse约定,您也可以将它们作为包含行和列的元组传递

>>> rows = [0, 1, 2, 3, 4]
>>> cols = [0, 0, 0, 1, 1]
>>> data = [10, 20, 30, 40, 50]
>>> z = COO((data, (rows, cols)), shape=(5, 2))
>>> z.todense()
array([[10,  0],
       [20,  0],
       [30,  0],
       [ 0, 40],
       [ 0, 50]])

您也可以传递一个字典或索引/值对的可迭代对象。重复的索引意味着求和

>>> d = {(0, 0, 0): 1, (1, 2, 3): 2, (1, 1, 0): 3}
>>> COO(d, shape=(2, 3, 4))
<COO: shape=(2, 3, 4), dtype=int64, nnz=3, fill_value=0>
>>> L = [((0, 0), 1), ((1, 1), 2), ((0, 0), 3)]
>>> COO(L, shape=(2, 2)).todense()
array([[4, 0],
       [0, 2]])

您可以将sparse.DOK数组转换为sparse.COO数组。

>>> from sparse import DOK
>>> s6 = DOK((5, 5), dtype=np.int64)
>>> s6[1:3, 1:3] = [[4, 5], [6, 7]]
>>> s6
<DOK: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
>>> s7 = s6.asformat("coo")
>>> s7
<COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
>>> s7.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/_coo/core.py
  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
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 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
 716
 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
 807
 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
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 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
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
class COO(SparseArray, NDArrayOperatorsMixin):  # lgtm [py/missing-equals]
    """
    A sparse multidimensional array.

    This is stored in COO format.  It depends on NumPy and Scipy.sparse for
    computation, but supports arrays of arbitrary dimension.

    Parameters
    ----------
    coords : numpy.ndarray (COO.ndim, COO.nnz)
        An array holding the index locations of every value
        Should have shape (number of dimensions, number of non-zeros).
    data : numpy.ndarray (COO.nnz,)
        An array of Values. A scalar can also be supplied if the data is the same across
        all coordinates. If not given, defers to [`sparse.as_coo`][].
    shape : tuple[int] (COO.ndim,)
        The shape of the array.
    has_duplicates : bool, optional
        A value indicating whether the supplied value for [`sparse.COO.coords`][] has
        duplicates. Note that setting this to `False` when `coords` does have
        duplicates may result in undefined behaviour.
    sorted : bool, optional
        A value indicating whether the values in `coords` are sorted. Note
        that setting this to `True` when [`sparse.COO.coords`][] isn't sorted may
        result in undefined behaviour.
    prune : bool, optional
        A flag indicating whether or not we should prune any fill-values present in
        `data`.
    cache : bool, optional
        Whether to enable cacheing for various operations. See
        [`sparse.COO.enable_caching`][].
    fill_value: scalar, optional
        The fill value for this array.

    Attributes
    ----------
    coords : numpy.ndarray (ndim, nnz)
        An array holding the coordinates of every nonzero element.
    data : numpy.ndarray (nnz,)
        An array holding the values corresponding to [`sparse.COO.coords`][].
    shape : tuple[int] (ndim,)
        The dimensions of this array.

    See Also
    --------
    - [`sparse.DOK`][]: A mostly write-only sparse array.
    - [`sparse.as_coo`][]: Convert any given format to [`sparse.COO`][].

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

    >>> x = np.eye(4, dtype=np.uint8)
    >>> x[2, 3] = 5
    >>> s = COO.from_numpy(x)
    >>> s
    <COO: shape=(4, 4), dtype=uint8, nnz=5, fill_value=0>
    >>> s.data  # doctest: +NORMALIZE_WHITESPACE
    array([1, 1, 1, 5, 1], dtype=uint8)
    >>> s.coords  # doctest: +NORMALIZE_WHITESPACE
    array([[0, 1, 2, 2, 3],
           [0, 1, 2, 3, 3]])

    [`sparse.COO`][] objects support basic arithmetic and binary operations.

    >>> x2 = np.eye(4, dtype=np.uint8)
    >>> x2[3, 2] = 5
    >>> s2 = COO.from_numpy(x2)
    >>> (s + s2).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[2, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 2, 5],
           [0, 0, 5, 2]], dtype=uint8)
    >>> (s * s2).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[1, 0, 0, 0],
           [0, 1, 0, 0],
           [0, 0, 1, 0],
           [0, 0, 0, 1]], dtype=uint8)

    Binary operations support broadcasting.

    >>> x3 = np.zeros((4, 1), dtype=np.uint8)
    >>> x3[2, 0] = 1
    >>> s3 = COO.from_numpy(x3)
    >>> (s * s3).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 1, 5],
           [0, 0, 0, 0]], dtype=uint8)

    [`sparse.COO`][] objects also support dot products and reductions.

    >>> s.dot(s.T).sum(axis=0).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([ 1,  1, 31,  6], dtype=uint64)

    You can use Numpy `ufunc` operations on [`sparse.COO`][] arrays as well.

    >>> np.sum(s, axis=1).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([1, 1, 6, 1], dtype=uint64)
    >>> np.round(np.sqrt(s, dtype=np.float64), decimals=1).todense()  # doctest: +SKIP
    array([[ 1. ,  0. ,  0. ,  0. ],
           [ 0. ,  1. ,  0. ,  0. ],
           [ 0. ,  0. ,  1. ,  2.2],
           [ 0. ,  0. ,  0. ,  1. ]])

    Operations that will result in a dense array will usually result in a different
    fill value, such as the following.

    >>> np.exp(s)
    <COO: shape=(4, 4), dtype=float16, nnz=5, fill_value=1.0>

    You can also create [`sparse.COO`][] arrays from coordinates and data.

    >>> coords = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 3], [0, 3, 2, 0, 1]]
    >>> data = [1, 2, 3, 4, 5]
    >>> s4 = COO(coords, data, shape=(3, 4, 5))
    >>> s4
    <COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>

    If the data is same across all coordinates, you can also specify a scalar.

    >>> coords = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 3], [0, 3, 2, 0, 1]]
    >>> data = 1
    >>> s5 = COO(coords, data, shape=(3, 4, 5))
    >>> s5
    <COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>

    Following scipy.sparse conventions you can also pass these as a tuple with
    rows and columns

    >>> rows = [0, 1, 2, 3, 4]
    >>> cols = [0, 0, 0, 1, 1]
    >>> data = [10, 20, 30, 40, 50]
    >>> z = COO((data, (rows, cols)), shape=(5, 2))
    >>> z.todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[10,  0],
           [20,  0],
           [30,  0],
           [ 0, 40],
           [ 0, 50]])

    You can also pass a dictionary or iterable of index/value pairs. Repeated
    indices imply summation:

    >>> d = {(0, 0, 0): 1, (1, 2, 3): 2, (1, 1, 0): 3}
    >>> COO(d, shape=(2, 3, 4))
    <COO: shape=(2, 3, 4), dtype=int64, nnz=3, fill_value=0>
    >>> L = [((0, 0), 1), ((1, 1), 2), ((0, 0), 3)]
    >>> COO(L, shape=(2, 2)).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[4, 0],
           [0, 2]])

    You can convert [`sparse.DOK`][] arrays to [`sparse.COO`][] arrays.

    >>> from sparse import DOK
    >>> s6 = DOK((5, 5), dtype=np.int64)
    >>> s6[1:3, 1:3] = [[4, 5], [6, 7]]
    >>> s6
    <DOK: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
    >>> s7 = s6.asformat("coo")
    >>> s7
    <COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
    >>> s7.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]])
    """

    __array_priority__ = 12

    def __init__(
        self,
        coords,
        data=None,
        shape=None,
        has_duplicates=True,
        sorted=False,
        prune=False,
        cache=False,
        fill_value=None,
        idx_dtype=None,
    ):
        if isinstance(coords, COO):
            self._make_shallow_copy_of(coords)
            if data is not None or shape is not None:
                raise ValueError("If `coords` is `COO`, then no other arguments should be provided.")
            if fill_value is not None:
                self.fill_value = self.data.dtype.type(fill_value)
            return

        self._cache = None
        if cache:
            self.enable_caching()

        if data is None:
            arr = as_coo(coords, shape=shape, fill_value=fill_value, idx_dtype=idx_dtype)
            self._make_shallow_copy_of(arr)
            if cache:
                self.enable_caching()
            return

        self.data = np.asarray(data)
        self.coords = np.asarray(coords)

        if self.coords.ndim == 1:
            if self.coords.size == 0 and shape is not None:
                self.coords = self.coords.reshape((len(shape), len(data)))
            else:
                self.coords = self.coords[None, :]

        if self.data.ndim == 0:
            self.data = np.broadcast_to(self.data, self.coords.shape[1])

        if self.data.ndim != 1:
            raise ValueError("`data` must be a scalar or 1-dimensional.")

        if shape is None:
            raise ValueError("`shape` was not provided.")

        if not isinstance(shape, Iterable):
            shape = (shape,)

        if isinstance(shape, np.ndarray):
            shape = tuple(shape)

        if shape and not self.coords.size:
            self.coords = np.zeros((len(shape) if isinstance(shape, Iterable) else 1, 0), dtype=np.intp)
        super().__init__(shape, fill_value=fill_value)
        if idx_dtype:
            if not can_store(idx_dtype, max(shape)):
                raise ValueError(f"cannot cast array with shape {shape} to dtype {idx_dtype}.")
            self.coords = self.coords.astype(idx_dtype)

        if self.shape:
            if len(self.data) != self.coords.shape[1]:
                msg = "The data length does not match the coordinates given.\nlen(data) = {}, but {} coords specified."
                raise ValueError(msg.format(len(data), self.coords.shape[1]))
            if len(self.shape) != self.coords.shape[0]:
                msg = (
                    "Shape specified by `shape` doesn't match the "
                    "shape of `coords`; len(shape)={} != coords.shape[0]={}"
                    "(and coords.shape={})"
                )
                raise ValueError(msg.format(len(shape), self.coords.shape[0], self.coords.shape))

        from .._settings import WARN_ON_TOO_DENSE

        if WARN_ON_TOO_DENSE and self.nbytes >= self.size * self.data.itemsize:
            warnings.warn(
                "Attempting to create a sparse array that takes no less "
                "memory than than an equivalent dense array. You may want to "
                "use a dense array here instead.",
                RuntimeWarning,
                stacklevel=1,
            )

        if not sorted:
            self._sort_indices()

        if has_duplicates:
            self._sum_duplicates()

        if prune:
            self._prune()

    def __getstate__(self):
        return (self.coords, self.data, self.shape, self.fill_value)

    def __setstate__(self, state):
        self.coords, self.data, self.shape, self.fill_value = state
        self._cache = None

    def __dask_tokenize__(self):
        "Produce a deterministic, content-based hash for dask."
        from dask.base import normalize_token

        return normalize_token((type(self), self.coords, self.data, self.shape, self.fill_value))

    def copy(self, deep=True):
        """Return a copy of the array.

        Parameters
        ----------
        deep : boolean, optional
            If True (default), the internal coords and data arrays are also
            copied. Set to ``False`` to only make a shallow copy.
        """
        return _copy.deepcopy(self) if deep else _copy.copy(self)

    def enable_caching(self):
        """Enable caching of reshape, transpose, and tocsr/csc operations

        This enables efficient iterative workflows that make heavy use of
        csr/csc operations, such as tensordot.  This maintains a cache of
        recent results of reshape and transpose so that operations like
        tensordot (which uses both internally) store efficiently stored
        representations for repeated use.  This can significantly cut down on
        computational costs in common numeric algorithms.

        However, this also assumes that neither this object, nor the downstream
        objects will have their data mutated.

        Examples
        --------
        >>> s.enable_caching()  # doctest: +SKIP
        >>> csr1 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()  # doctest: +SKIP
        >>> csr2 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()  # doctest: +SKIP
        >>> csr1 is csr2  # doctest: +SKIP
        True
        """
        self._cache = defaultdict(lambda: deque(maxlen=3))

    @classmethod
    def from_numpy(cls, x, fill_value=None, idx_dtype=None):
        """
        Convert the given [`sparse.COO`][] object.

        Parameters
        ----------
        x : np.ndarray
            The dense array to convert.
        fill_value : scalar
            The fill value of the constructed [`sparse.COO`][] array. Zero if
            unspecified.

        Returns
        -------
        COO
            The converted COO array.

        Examples
        --------
        >>> x = np.eye(5)
        >>> s = COO.from_numpy(x)
        >>> s
        <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=0.0>

        >>> x[x == 0] = np.nan
        >>> COO.from_numpy(x, fill_value=np.nan)
        <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=nan>
        """
        x = np.asanyarray(x).view(type=np.ndarray)

        if fill_value is None:
            fill_value = _zero_of_dtype(x.dtype) if x.shape else x

        coords = np.atleast_2d(np.flatnonzero(~equivalent(x, fill_value)))
        data = x.ravel()[tuple(coords)]
        return cls(
            coords,
            data,
            shape=x.size,
            has_duplicates=False,
            sorted=True,
            fill_value=fill_value,
            idx_dtype=idx_dtype,
        ).reshape(x.shape)

    def todense(self):
        """
        Convert this [`sparse.COO`][] array to a dense [`numpy.ndarray`][]. Note that
        this may take a large amount of memory if the `COO` object's `shape`
        is large.

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

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

        Examples
        --------
        >>> x = np.random.randint(100, size=(7, 3))
        >>> s = COO.from_numpy(x)
        >>> x2 = s.todense()
        >>> np.array_equal(x, x2)
        True
        """
        x = np.full(self.shape, self.fill_value, self.dtype)

        coords = tuple([self.coords[i, :] for i in range(self.ndim)])
        data = self.data

        if len(coords) != 0:
            x[coords] = data
        else:
            if len(data) != 0:
                assert data.shape == (1,)
                x[...] = data[0]

        return x

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

        Parameters
        ----------
        x : scipy.sparse.spmatrix
            The sparse matrix to construct the array from.
        fill_value : scalar
            The fill-value to use when converting.

        Returns
        -------
        COO
            The converted [`sparse.COO`][] object.

        Examples
        --------
        >>> import scipy.sparse
        >>> x = scipy.sparse.rand(6, 3, density=0.2)
        >>> s = COO.from_scipy_sparse(x)
        >>> np.array_equal(x.todense(), s.todense())
        True
        """
        x = x.asformat("coo")
        if not x.has_canonical_format:
            x.eliminate_zeros()
            x.sum_duplicates()

        coords = np.empty((2, x.nnz), dtype=x.row.dtype)
        coords[0, :] = x.row
        coords[1, :] = x.col
        return COO(
            coords,
            x.data,
            shape=x.shape,
            has_duplicates=not x.has_canonical_format,
            sorted=x.has_canonical_format,
            fill_value=fill_value,
        )

    @classmethod
    def from_iter(cls, x, shape, fill_value=None, dtype=None):
        """
        Converts an iterable in certain formats to a [`sparse.COO`][] array. See examples
        for details.

        Parameters
        ----------
        x : Iterable or Iterator
            The iterable to convert to [`sparse.COO`][].
        shape : tuple[int]
            The shape of the array.
        fill_value : scalar
            The fill value for this array.
        dtype : numpy.dtype
            The dtype of the input array. Inferred from the input if not given.

        Returns
        -------
        out : COO
            The output [`sparse.COO`][] array.

        Examples
        --------
        You can convert items of the format [`sparse.COO`][].
        Here, the first part represents the coordinate and the second part represents the value.

        >>> x = [((0, 0), 1), ((1, 1), 1)]
        >>> s = COO.from_iter(x, shape=(2, 2))
        >>> s.todense()
        array([[1, 0],
               [0, 1]])

        You can also have a similar format with a dictionary.

        >>> x = {(0, 0): 1, (1, 1): 1}
        >>> s = COO.from_iter(x, shape=(2, 2))
        >>> s.todense()
        array([[1, 0],
               [0, 1]])

        The third supported format is ``(data, (..., row, col))``.

        >>> x = ([1, 1], ([0, 1], [0, 1]))
        >>> s = COO.from_iter(x, shape=(2, 2))
        >>> s.todense()
        array([[1, 0],
               [0, 1]])

        You can also pass in a [`collections.abc.Iterator`][] object.

        >>> x = [((0, 0), 1), ((1, 1), 1)].__iter__()
        >>> s = COO.from_iter(x, shape=(2, 2))
        >>> s.todense()
        array([[1, 0],
               [0, 1]])
        """
        if isinstance(x, dict):
            x = list(x.items())

        if not isinstance(x, Sized):
            x = list(x)

        if len(x) != 2 and not all(len(item) == 2 for item in x):
            raise ValueError("Invalid iterable to convert to COO.")

        if not x:
            ndim = 0 if shape is None else len(shape)
            coords = np.empty((ndim, 0), dtype=np.uint8)
            data = np.empty((0,), dtype=dtype)
            shape = () if shape is None else shape

        elif not isinstance(x[0][0], Iterable):
            coords = np.stack(x[1], axis=0)
            data = np.asarray(x[0], dtype=dtype)
        else:
            coords = np.array([item[0] for item in x]).T
            data = np.array([item[1] for item in x], dtype=dtype)

        if not (
            coords.ndim == 2 and data.ndim == 1 and np.issubdtype(coords.dtype, np.integer) and np.all(coords >= 0)
        ):
            raise ValueError("Invalid iterable to convert to COO.")

        return COO(coords, data, shape=shape, fill_value=fill_value)

    @property
    def dtype(self):
        """
        The datatype of this array.

        Returns
        -------
        numpy.dtype
            The datatype of this array.

        See Also
        --------
        - [`numpy.ndarray.dtype`][] : Numpy equivalent property.
        - [`scipy.sparse.coo_matrix.dtype`][] : Scipy equivalent property.

        Examples
        --------
        >>> x = (200 * np.random.rand(5, 4)).astype(np.int32)
        >>> s = COO.from_numpy(x)
        >>> s.dtype
        dtype('int32')
        >>> x.dtype == s.dtype
        True
        """
        return self.data.dtype

    @property
    def nnz(self):
        """
        The number of nonzero elements in this array. Note that any duplicates in
        `coords` are counted multiple times.

        Returns
        -------
        int
            The number of nonzero elements in this array.

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

        Examples
        --------
        >>> x = np.array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 0])
        >>> np.count_nonzero(x)
        6
        >>> s = COO.from_numpy(x)
        >>> s.nnz
        6
        >>> np.count_nonzero(x) == s.nnz
        True
        """
        return self.coords.shape[1]

    @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 "coo"

    @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
        --------
        >>> data = np.arange(6, dtype=np.uint8)
        >>> coords = np.random.randint(1000, size=(3, 6), dtype=np.uint16)
        >>> s = COO(coords, data, shape=(1000, 1000, 1000))
        >>> s.nbytes
        42
        """
        return self.data.nbytes + self.coords.nbytes

    def __len__(self):
        """
        Get "length" of array, which is by definition the size of the first
        dimension.

        Returns
        -------
        int
            The size of the first dimension.

        See Also
        --------
        numpy.ndarray.__len__ : Numpy equivalent property.

        Examples
        --------
        >>> x = np.zeros((10, 10))
        >>> s = COO.from_numpy(x)
        >>> len(s)
        10
        """
        return self.shape[0]

    def __sizeof__(self):
        return self.nbytes

    __getitem__ = getitem

    def __str__(self):
        summary = f"<COO: 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 _reduce_calc(self, method, axis, keepdims=False, **kwargs):
        if axis == (None,):
            axis = tuple(range(self.ndim))
        axis = tuple(a if a >= 0 else a + self.ndim for a in axis)
        neg_axis = tuple(ax for ax in range(self.ndim) if ax not in set(axis))
        a = self.transpose(neg_axis + axis)
        a = a.reshape(
            (
                np.prod([self.shape[d] for d in neg_axis], dtype=np.intp),
                np.prod([self.shape[d] for d in axis], dtype=np.intp),
            )
        )
        data, inv_idx, counts = _grouped_reduce(a.data, a.coords[0], method, **kwargs)
        n_cols = a.shape[1]
        arr_attrs = (a, neg_axis, inv_idx)
        return (data, counts, axis, n_cols, arr_attrs)

    def _reduce_return(self, data, arr_attrs, result_fill_value):
        a, neg_axis, inv_idx = arr_attrs
        coords = a.coords[0:1, inv_idx]
        out = COO(
            coords,
            data,
            shape=(a.shape[0],),
            has_duplicates=False,
            sorted=True,
            prune=True,
            fill_value=result_fill_value,
        )

        return out.reshape(tuple(self.shape[d] for d in neg_axis))

    def transpose(self, axes=None):
        """
        Returns a new array which has the order of the axes switched.

        Parameters
        ----------
        axes : Iterable[int], optional
            The new order of the axes compared to the previous one. Reverses the axes
            by default.

        Returns
        -------
        COO
            The new array with the axes in the desired order.

        See Also
        --------
        - [`sparse.COO.T`][] : A quick property to reverse the order of the axes.
        - [`numpy.ndarray.transpose`][] : Numpy equivalent function.

        Examples
        --------
        We can change the order of the dimensions of any [`sparse.COO`][] array with this
        function.

        >>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
        >>> x  # doctest: +NORMALIZE_WHITESPACE
        array([[4, 3, 2, 1, 0],
               [5, 4, 3, 2, 1],
               [6, 5, 4, 3, 2],
               [7, 6, 5, 4, 3],
               [8, 7, 6, 5, 4]])
        >>> s = COO.from_numpy(x)
        >>> s.transpose((1, 0)).todense()  # doctest: +NORMALIZE_WHITESPACE
        array([[4, 5, 6, 7, 8],
               [3, 4, 5, 6, 7],
               [2, 3, 4, 5, 6],
               [1, 2, 3, 4, 5],
               [0, 1, 2, 3, 4]])

        Note that by default, this reverses the order of the axes rather than switching
        the last and second-to-last axes as required by some linear algebra operations.

        >>> x = np.random.rand(2, 3, 4)
        >>> s = COO.from_numpy(x)
        >>> s.transpose().shape
        (4, 3, 2)
        """
        if axes is None:
            axes = list(reversed(range(self.ndim)))

        # Normalize all axes indices to positive values
        axes = normalize_axis(axes, self.ndim)

        if len(np.unique(axes)) < len(axes):
            raise ValueError("repeated axis in transpose")

        if not len(axes) == self.ndim:
            raise ValueError("axes don't match array")

        axes = tuple(axes)

        if axes == tuple(range(self.ndim)):
            return self

        if self._cache is not None:
            for ax, value in self._cache["transpose"]:
                if ax == axes:
                    return value

        shape = tuple(self.shape[ax] for ax in axes)
        result = COO(
            self.coords[axes, :],
            self.data,
            shape,
            has_duplicates=False,
            cache=self._cache is not None,
            fill_value=self.fill_value,
        )

        if self._cache is not None:
            self._cache["transpose"].append((axes, result))
        return result

    @property
    def T(self):
        """
        Returns a new array which has the order of the axes reversed.

        Returns
        -------
        COO
            The new array with the axes in the desired order.

        See Also
        --------
        - [`sparse.COO.transpose`][] :
            A method where you can specify the order of the axes.
        - [`numpy.ndarray.T`][] :
            Numpy equivalent property.

        Examples
        --------
        We can change the order of the dimensions of any [`sparse.COO`][] array with this
        function.

        >>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
        >>> x  # doctest: +NORMALIZE_WHITESPACE
        array([[4, 3, 2, 1, 0],
               [5, 4, 3, 2, 1],
               [6, 5, 4, 3, 2],
               [7, 6, 5, 4, 3],
               [8, 7, 6, 5, 4]])
        >>> s = COO.from_numpy(x)
        >>> s.T.todense()  # doctest: +NORMALIZE_WHITESPACE
        array([[4, 5, 6, 7, 8],
               [3, 4, 5, 6, 7],
               [2, 3, 4, 5, 6],
               [1, 2, 3, 4, 5],
               [0, 1, 2, 3, 4]])

        Note that by default, this reverses the order of the axes rather than switching
        the last and second-to-last axes as required by some linear algebra operations.

        >>> x = np.random.rand(2, 3, 4)
        >>> s = COO.from_numpy(x)
        >>> s.T.shape
        (4, 3, 2)
        """
        return self.transpose(tuple(range(self.ndim))[::-1])

    @property
    def mT(self):
        """
        Transpose of a matrix (or a stack of matrices).
        If an array instance has fewer than two dimensions, an error should be raised.

        Returns
        -------
        COO
            array whose last two dimensions (axes) are permuted in reverse order relative to
            original array (i.e., for an array instance having shape (..., M, N), the returned
            array must have shape (..., N, M)). The returned array must have the same data
            type as the original array.

        See Also
        --------
        - [`sparse.COO.transpose`][] :
            A method where you can specify the order of the axes.
        - [`numpy.ndarray.mT`][] :
            Numpy equivalent property.

        Examples
        --------
        >>> x = np.arange(8).reshape((2, 2, 2))
        >>> x  # doctest: +NORMALIZE_WHITESPACE
        array([[[0, 1],
                [2, 3]],
               [[4, 5],
                [6, 7]]])
        >>> s = COO.from_numpy(x)
        >>> s.mT.todense()  # doctest: +NORMALIZE_WHITESPACE
        array([[[0, 2],
                [1, 3]],
               [[4, 6],
                [5, 7]]])
        """
        if self.ndim < 2:
            raise ValueError("Cannot compute matrix transpose if `ndim < 2`.")

        axis = list(range(self.ndim))
        axis[-1], axis[-2] = axis[-2], axis[-1]

        return self.transpose(axis)

    def swapaxes(self, axis1, axis2):
        """Returns array that has axes axis1 and axis2 swapped.

        Parameters
        ----------
        axis1 : int
            first axis to swap
        axis2 : int
            second axis to swap

        Returns
        -------
        COO
            The new array with the axes axis1 and axis2 swapped.

        Examples
        --------
        >>> x = COO.from_numpy(np.ones((2, 3, 4)))
        >>> x.swapaxes(0, 2)
        <COO: shape=(4, 3, 2), dtype=float64, nnz=24, fill_value=0.0>
        """
        # Normalize all axis1, axis2 to positive values
        axis1, axis2 = normalize_axis((axis1, axis2), self.ndim)  # checks if axis1,2 are in range + raises ValueError
        axes = list(range(self.ndim))
        axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
        return self.transpose(axes)

    def dot(self, other):
        """
        Performs the equivalent of `x.dot(y)` for [`sparse.COO`][].

        Parameters
        ----------
        other : Union[COO, numpy.ndarray, scipy.sparse.spmatrix]
            The second operand of the dot product operation.

        Returns
        -------
        {COO, numpy.ndarray}
            The result of the dot product. If the result turns out to be dense,
            then a dense array is returned, otherwise, a sparse array.

        Raises
        ------
        ValueError
            If all arguments don't have zero fill-values.

        See Also
        --------
        - [`sparse.dot`][] : Equivalent function for two arguments.
        - [`numpy.dot`][] : Numpy equivalent function.
        - [`scipy.sparse.coo_matrix.dot`][] : Scipy equivalent function.

        Examples
        --------
        >>> x = np.arange(4).reshape((2, 2))
        >>> s = COO.from_numpy(x)
        >>> s.dot(s)  # doctest: +SKIP
        array([[ 2,  3],
               [ 6, 11]], dtype=int64)
        """
        from .._common import dot

        return dot(self, other)

    def __matmul__(self, other):
        from .._common import matmul

        try:
            return matmul(self, other)
        except NotImplementedError:
            return NotImplemented

    def __rmatmul__(self, other):
        from .._common import matmul

        try:
            return matmul(other, self)
        except NotImplementedError:
            return NotImplemented

    def linear_loc(self):
        """
        The nonzero coordinates of a flattened version of this array. Note that
        the coordinates may be out of order.

        Returns
        -------
        numpy.ndarray
            The flattened coordinates.

        See Also
        --------
        [`numpy.flatnonzero`][] : Equivalent Numpy function.

        Examples
        --------
        >>> x = np.eye(5)
        >>> s = COO.from_numpy(x)
        >>> s.linear_loc()  # doctest: +NORMALIZE_WHITESPACE
        array([ 0,  6, 12, 18, 24])
        >>> np.array_equal(np.flatnonzero(x), s.linear_loc())
        True
        """
        from .common import linear_loc

        return linear_loc(self.coords, self.shape)

    def flatten(self, order="C"):
        """
        Returns a new [`sparse.COO`][] array that is a flattened version of this array.

        Returns
        -------
        COO
            The flattened output array.

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

        Examples
        --------
        >>> s = COO.from_numpy(np.arange(10))
        >>> s2 = s.reshape((2, 5)).flatten()
        >>> s2.todense()
        array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
        """
        if order not in {"C", None}:
            raise NotImplementedError("The `order` parameter is notsupported.")

        return self.reshape(-1)

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

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

        Returns
        -------
        COO
            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 = COO.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]])
        """
        shape = tuple(shape) if isinstance(shape, Iterable) else (shape,)

        if order not in {"C", None}:
            raise NotImplementedError("The `order` parameter is not supported")

        if self.shape == shape:
            return self
        if any(d == -1 for d in shape):
            extra = int(self.size / np.prod([d for d in shape if d != -1]))
            shape = tuple([d if d != -1 else extra for d in shape])

        if self.size != reduce(operator.mul, shape, 1):
            raise ValueError(f"cannot reshape array of size {self.size} into shape {shape}")

        if self._cache is not None:
            for sh, value in self._cache["reshape"]:
                if sh == shape:
                    return value

        # TODO: this self.size enforces a 2**64 limit to array size
        linear_loc = self.linear_loc()

        idx_dtype = self.coords.dtype
        if shape != () and not can_store(idx_dtype, max(shape)):
            idx_dtype = np.min_scalar_type(max(shape))
        coords = np.empty((len(shape), self.nnz), dtype=idx_dtype)
        strides = 1
        for i, d in enumerate(shape[::-1]):
            coords[-(i + 1), :] = (linear_loc // strides) % d
            strides *= d

        result = COO(
            coords,
            self.data,
            shape,
            has_duplicates=False,
            sorted=True,
            cache=self._cache is not None,
            fill_value=self.fill_value,
        )

        if self._cache is not None:
            self._cache["reshape"].append((shape, result))
        return result

    def squeeze(self, axis=None):
        """
        Removes singleton dimensions (axes) from ``x``.
        Parameters
        ----------
        axis : Union[None, int, Tuple[int, ...]]
            The axis (or axes) to squeeze. If a specified axis has a size greater than one,
            a `ValueError` is raised. ``axis=None`` removes all singleton dimensions.
            Default: ``None``.
        Returns
        -------
        COO
            The output array without ``axis`` dimensions.
        Examples
        --------
        >>> s = COO.from_numpy(np.eye(2)).reshape((2, 1, 2, 1))
        >>> s.squeeze().shape
        (2, 2)
        >>> s.squeeze(axis=1).shape
        (2, 2, 1)
        """
        squeezable_dims = tuple([d for d in range(self.ndim) if self.shape[d] == 1])

        if axis is None:
            axis = squeezable_dims
        if isinstance(axis, int):
            axis = (axis,)
        elif isinstance(axis, Iterable):
            axis = tuple(axis)
        else:
            raise ValueError(f"Invalid axis parameter: `{axis}`.")

        for d in axis:
            if d not in squeezable_dims:
                raise ValueError(f"Specified axis `{d}` has a size greater than one: {self.shape[d]}")

        retained_dims = [d for d in range(self.ndim) if d not in axis]

        coords = self.coords[retained_dims, :]
        shape = tuple([s for idx, s in enumerate(self.shape) if idx in retained_dims])

        return COO(
            coords,
            self.data,
            shape,
            has_duplicates=False,
            sorted=True,
            cache=self._cache is not None,
            fill_value=self.fill_value,
        )

    def to_scipy_sparse(self, /, *, accept_fv=None):
        """
        Converts this [`sparse.COO`][] object into a [`scipy.sparse.coo_matrix`][].

        Parameters
        ----------
        accept_fv : scalar or list of scalar, optional
            The list of accepted fill-values. The default accepts only zero.

        Returns
        -------
        scipy.sparse.coo_matrix
            The converted Scipy sparse matrix.

        Raises
        ------
        ValueError
            If the array is not two-dimensional.
        ValueError
            If all the array doesn't zero fill-values.

        See Also
        --------
        - [`sparse.COO.tocsr`][] : Convert to a [`scipy.sparse.csr_matrix`][].
        - [`sparse.COO.tocsc`][] : Convert to a [`scipy.sparse.csc_matrix`][].
        """
        import scipy.sparse

        check_fill_value(self, accept_fv=accept_fv)

        if self.ndim != 2:
            raise ValueError("Can only convert a 2-dimensional array to a Scipy sparse matrix.")

        result = scipy.sparse.coo_matrix((self.data, (self.coords[0], self.coords[1])), shape=self.shape)
        result.has_canonical_format = True
        return result

    def _tocsr(self):
        import scipy.sparse

        if self.ndim != 2:
            raise ValueError("This array must be two-dimensional for this conversion to work.")
        row, col = self.coords

        # Pass 3: count nonzeros in each row
        indptr = np.zeros(self.shape[0] + 1, dtype=np.int64)
        np.cumsum(np.bincount(row, minlength=self.shape[0]), out=indptr[1:])

        return scipy.sparse.csr_matrix((self.data, col, indptr), shape=self.shape)

    def tocsr(self):
        """
        Converts this array to a [`scipy.sparse.csr_matrix`][].

        Returns
        -------
        scipy.sparse.csr_matrix
            The result of the conversion.

        Raises
        ------
        ValueError
            If the array is not two-dimensional.
        ValueError
            If all the array doesn't have zero fill-values.

        See Also
        --------
        - [`sparse.COO.tocsc`][] : Convert to a [`scipy.sparse.csc_matrix`][].
        - [`sparse.COO.to_scipy_sparse`][] : Convert to a [`scipy.sparse.coo_matrix`][].
        - [`scipy.sparse.coo_matrix.tocsr`][] : Equivalent Scipy function.
        """
        check_zero_fill_value(self)

        if self._cache is not None:
            try:
                return self._csr
            except AttributeError:
                pass
            try:
                self._csr = self._csc.tocsr()
                return self._csr
            except AttributeError:
                pass

            self._csr = csr = self._tocsr()
        else:
            csr = self._tocsr()
        return csr

    def tocsc(self):
        """
        Converts this array to a [`scipy.sparse.csc_matrix`][].

        Returns
        -------
        scipy.sparse.csc_matrix
            The result of the conversion.

        Raises
        ------
        ValueError
            If the array is not two-dimensional.
        ValueError
            If the array doesn't have zero fill-values.

        See Also
        --------
        - [`sparse.COO.tocsr`][] : Convert to a [`scipy.sparse.csr_matrix`][].
        - [`sparse.COO.to_scipy_sparse`][] : Convert to a [`scipy.sparse.coo_matrix`][].
        - [`scipy.sparse.coo_matrix.tocsc`][] : Equivalent Scipy function.
        """
        check_zero_fill_value(self)

        if self._cache is not None:
            try:
                return self._csc
            except AttributeError:
                pass
            try:
                self._csc = self._csr.tocsc()
                return self._csc
            except AttributeError:
                pass

            self._csc = csc = self.tocsr().tocsc()
        else:
            csc = self.tocsr().tocsc()

        return csc

    def _sort_indices(self):
        """
        Sorts the :obj:`COO.coords` attribute. Also sorts the data in
        :obj:`COO.data` to match.

        Examples
        --------
        >>> coords = np.array([[1, 2, 0]], dtype=np.uint8)
        >>> data = np.array([4, 1, 3], dtype=np.uint8)
        >>> s = COO(coords, data, shape=(3,))
        >>> s._sort_indices()
        >>> s.coords  # doctest: +NORMALIZE_WHITESPACE
        array([[0, 1, 2]], dtype=uint8)
        >>> s.data  # doctest: +NORMALIZE_WHITESPACE
        array([3, 4, 1], dtype=uint8)
        """
        linear = self.linear_loc()

        if (np.diff(linear) >= 0).all():  # already sorted
            return

        order = np.argsort(linear, kind="mergesort")
        self.coords = self.coords[:, order]
        self.data = self.data[order]

    def _sum_duplicates(self):
        """
        Sums data corresponding to duplicates in :obj:`COO.coords`.

        See Also
        --------
        scipy.sparse.coo_matrix.sum_duplicates : Equivalent Scipy function.

        Examples
        --------
        >>> coords = np.array([[0, 1, 1, 2]], dtype=np.uint8)
        >>> data = np.array([6, 5, 2, 2], dtype=np.uint8)
        >>> s = COO(coords, data, shape=(3,))
        >>> s._sum_duplicates()
        >>> s.coords  # doctest: +NORMALIZE_WHITESPACE
        array([[0, 1, 2]], dtype=uint8)
        >>> s.data  # doctest: +NORMALIZE_WHITESPACE
        array([6, 7, 2], dtype=uint8)
        """
        # Inspired by scipy/sparse/coo.py::sum_duplicates
        # See https://github.com/scipy/scipy/blob/main/LICENSE.txt
        linear = self.linear_loc()
        unique_mask = np.diff(linear) != 0

        if unique_mask.sum() == len(unique_mask):  # already unique
            return

        unique_mask = np.append(True, unique_mask)

        coords = self.coords[:, unique_mask]
        (unique_inds,) = np.nonzero(unique_mask)
        data = np.add.reduceat(self.data, unique_inds, dtype=self.data.dtype)

        self.data = data
        self.coords = coords

    def _prune(self):
        """
        Prunes data so that if any fill-values are present, they are removed
        from both coordinates and data.

        Examples
        --------
        >>> coords = np.array([[0, 1, 2, 3]])
        >>> data = np.array([1, 0, 1, 2])
        >>> s = COO(coords, data, shape=(4,))
        >>> s._prune()
        >>> s.nnz
        3
        """
        mask = ~equivalent(self.data, self.fill_value)
        self.coords = self.coords[:, mask]
        self.data = self.data[mask]

    def broadcast_to(self, shape):
        """
        Performs the equivalent of [`sparse.COO`][]. Note that
        this function returns a new array instead of a view.

        Parameters
        ----------
        shape : tuple[int]
            The shape to broadcast the data to.

        Returns
        -------
        COO
            The broadcasted sparse array.

        Raises
        ------
        ValueError
            If the operand cannot be broadcast to the given shape.

        See Also
        --------
        [`numpy.broadcast_to`][] : NumPy equivalent function
        """
        return broadcast_to(self, shape)

    def maybe_densify(self, max_size=1000, min_density=0.25):
        """
        Converts this [`sparse.COO`][] array to a [`numpy.ndarray`][] if not too
        costly.

        Parameters
        ----------
        max_size : int
            Maximum number of elements in output
        min_density : float
            Minimum density of output

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

        Raises
        ------
        ValueError
            If the returned array would be too large.

        Examples
        --------
        Convert a small sparse array to a dense array.

        >>> s = COO.from_numpy(np.random.rand(2, 3, 4))
        >>> x = s.maybe_densify()
        >>> np.allclose(x, s.todense())
        True

        You can also specify the minimum allowed density or the maximum number
        of output elements. If both conditions are unmet, this method will throw
        an error.

        >>> x = np.zeros((5, 5), dtype=np.uint8)
        >>> x[2, 2] = 1
        >>> s = COO.from_numpy(x)
        >>> s.maybe_densify(max_size=5, min_density=0.25)
        Traceback (most recent call last):
            ...
        ValueError: Operation would require converting large sparse array to dense
        """
        if self.size > max_size and self.density < min_density:
            raise ValueError("Operation would require converting large sparse array to dense")

        return self.todense()

    def nonzero(self):
        """
        Get the indices where this array is nonzero.

        Returns
        -------
        idx : tuple[`numpy.ndarray`]
            The indices where this array is nonzero.

        See Also
        --------
        [`numpy.ndarray.nonzero`][] : NumPy equivalent function

        Raises
        ------
        ValueError
            If the array doesn't have zero fill-values.

        Examples
        --------
        >>> s = COO.from_numpy(np.eye(5))
        >>> s.nonzero()
        (array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))
        """
        check_zero_fill_value(self)
        if self.ndim == 0:
            raise ValueError("`nonzero` is undefined for `self.ndim == 0`.")
        return tuple(self.coords)

    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 == "gcxs":
            from .._compressed import GCXS

            return GCXS.from_coo(self, **kwargs)

        if len(kwargs) != 0:
            raise TypeError(f"Invalid keyword arguments provided: {kwargs}")

        if format == "coo":
            return self

        if format == "dok":
            from .._dok import DOK

            return DOK.from_coo(self, **kwargs)

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

    def isinf(self):
        """
        Tests each element ``x_i`` of the array to determine if equal to positive or negative infinity.
        """
        new_fill_value = bool(np.isinf(self.fill_value))
        new_data = np.isinf(self.data)

        return COO(
            self.coords,
            new_data,
            shape=self.shape,
            fill_value=new_fill_value,
            prune=True,
        )

    def isnan(self):
        """
        Tests each element ``x_i`` of the array to determine whether the element is ``NaN``.
        """
        new_fill_value = bool(np.isnan(self.fill_value))
        new_data = np.isnan(self.data)

        return COO(
            self.coords,
            new_data,
            shape=self.shape,
            fill_value=new_fill_value,
            prune=True,
        )

属性

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

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')

返回

名称 类型 描述
输出 SparseArray

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

另请参阅

imag 属性

数组的虚部。

示例

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

返回

名称 类型 描述
输出 SparseArray

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

另请参阅

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

data = np.asarray(data) 实例属性

coords = np.asarray(coords) 实例属性

dtype 属性

此数组的数据类型。

返回

类型 描述
dtype

此数组的数据类型。

另请参阅

示例

>>> x = (200 * np.random.rand(5, 4)).astype(np.int32)
>>> s = COO.from_numpy(x)
>>> s.dtype
dtype('int32')
>>> x.dtype == s.dtype
True

nnz 属性

此数组中非零元素的数量。请注意,coords中的任何重复项都会被多次计数。

返回

类型 描述
int

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

另请参阅

示例

>>> x = np.array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 0])
>>> np.count_nonzero(x)
6
>>> s = COO.from_numpy(x)
>>> s.nnz
6
>>> np.count_nonzero(x) == s.nnz
True

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的等效属性。

示例

>>> data = np.arange(6, dtype=np.uint8)
>>> coords = np.random.randint(1000, size=(3, 6), dtype=np.uint16)
>>> s = COO(coords, data, shape=(1000, 1000, 1000))
>>> s.nbytes
42

T 属性

返回一个新数组,其轴的顺序已反转。

返回

类型 描述
COO

轴以所需顺序排列的新数组。

另请参阅

示例

我们可以使用此函数更改任何sparse.COO数组的维度顺序。

>>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
>>> x
array([[4, 3, 2, 1, 0],
       [5, 4, 3, 2, 1],
       [6, 5, 4, 3, 2],
       [7, 6, 5, 4, 3],
       [8, 7, 6, 5, 4]])
>>> s = COO.from_numpy(x)
>>> s.T.todense()
array([[4, 5, 6, 7, 8],
       [3, 4, 5, 6, 7],
       [2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4]])

请注意,默认情况下,这会反转轴的顺序,而不是根据某些线性代数操作的要求切换倒数第二和倒数第一轴。

>>> x = np.random.rand(2, 3, 4)
>>> s = COO.from_numpy(x)
>>> s.T.shape
(4, 3, 2)

mT 属性

矩阵(或矩阵堆栈)的转置。如果数组实例的维度少于两个,则应引发错误。

返回

类型 描述
COO

数组的最后两个维度(轴)相对于原始数组以相反顺序排列(即,对于形状为(..., M, N)的数组实例,返回的数组必须具有形状(..., N, M))。返回的数组必须与原始数组具有相同的数据类型。

另请参阅

示例

>>> x = np.arange(8).reshape((2, 2, 2))
>>> x
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> s = COO.from_numpy(x)
>>> s.mT.todense()
array([[[0, 2],
        [1, 3]],
       [[4, 6],
        [5, 7]]])

函数

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]]

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

keepdims bool_

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

False
dtype dtype

输出数组的数据类型。

返回

类型 描述
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]]

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

keepdims bool_

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

False
输出 dtype

输出数组的数据类型。

返回

类型 描述
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]]

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

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]]

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

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]]

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

keepdims bool_

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

False
输出 dtype

输出数组的数据类型。

返回

类型 描述
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]]

求乘积的轴。默认使用所有轴。

keepdims bool_

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

False
dtype dtype

输出数组的数据类型。

返回

类型 描述
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]]

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

keepdims bool_

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

False
dtype dtype

输出数组的数据类型。

返回

类型 描述
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]]

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

dtype dtype

输出数据类型。

输出 SparseArray

写入输出的数组。

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]]

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

dtype dtype

输出数据类型。

输出 SparseArray

写入输出的数组。

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')

返回

名称 类型 描述
输出 SparseArray

复共轭,与输入具有相同的数据类型。

另请参阅
源代码位于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)

copy(deep=True)

返回数组的副本。

参数

名称 类型 描述 默认值
deep boolean

如果为True(默认值),则内部的coords和data数组也会被复制。设置为False则只进行浅复制。

True
源代码位于sparse/numba_backend/_coo/core.py
306
307
308
309
310
311
312
313
314
315
def copy(self, deep=True):
    """Return a copy of the array.

    Parameters
    ----------
    deep : boolean, optional
        If True (default), the internal coords and data arrays are also
        copied. Set to ``False`` to only make a shallow copy.
    """
    return _copy.deepcopy(self) if deep else _copy.copy(self)

enable_caching()

启用重塑、转置和tocsr/csc操作的缓存

这使得高效的迭代工作流成为可能,这些工作流大量使用csr/csc操作,例如tensordot。这会维护一个重塑和转置操作的近期结果缓存,以便像tensordot(内部同时使用两者)这样的操作可以存储高效的表示以供重复使用。这可以显著降低常见数值算法的计算成本。

但是,这也假定此对象及其下游对象都不会修改其数据。

示例

>>> s.enable_caching()
>>> csr1 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()
>>> csr2 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()
>>> csr1 is csr2
True
源代码位于sparse/numba_backend/_coo/core.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def enable_caching(self):
    """Enable caching of reshape, transpose, and tocsr/csc operations

    This enables efficient iterative workflows that make heavy use of
    csr/csc operations, such as tensordot.  This maintains a cache of
    recent results of reshape and transpose so that operations like
    tensordot (which uses both internally) store efficiently stored
    representations for repeated use.  This can significantly cut down on
    computational costs in common numeric algorithms.

    However, this also assumes that neither this object, nor the downstream
    objects will have their data mutated.

    Examples
    --------
    >>> s.enable_caching()  # doctest: +SKIP
    >>> csr1 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()  # doctest: +SKIP
    >>> csr2 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr()  # doctest: +SKIP
    >>> csr1 is csr2  # doctest: +SKIP
    True
    """
    self._cache = defaultdict(lambda: deque(maxlen=3))

from_numpy(x, fill_value=None, idx_dtype=None) 类方法

转换给定的sparse.COO对象。

参数

名称 类型 描述 默认值
x ndarray

要转换的密集数组。

必填
fill_value scalar

构建的sparse.COO数组的填充值。如果未指定,则为零。

返回

类型 描述
COO

转换后的COO数组。

示例

>>> x = np.eye(5)
>>> s = COO.from_numpy(x)
>>> s
<COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=0.0>
>>> x[x == 0] = np.nan
>>> COO.from_numpy(x, fill_value=np.nan)
<COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=nan>
源代码位于sparse/numba_backend/_coo/core.py
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
@classmethod
def from_numpy(cls, x, fill_value=None, idx_dtype=None):
    """
    Convert the given [`sparse.COO`][] object.

    Parameters
    ----------
    x : np.ndarray
        The dense array to convert.
    fill_value : scalar
        The fill value of the constructed [`sparse.COO`][] array. Zero if
        unspecified.

    Returns
    -------
    COO
        The converted COO array.

    Examples
    --------
    >>> x = np.eye(5)
    >>> s = COO.from_numpy(x)
    >>> s
    <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=0.0>

    >>> x[x == 0] = np.nan
    >>> COO.from_numpy(x, fill_value=np.nan)
    <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=nan>
    """
    x = np.asanyarray(x).view(type=np.ndarray)

    if fill_value is None:
        fill_value = _zero_of_dtype(x.dtype) if x.shape else x

    coords = np.atleast_2d(np.flatnonzero(~equivalent(x, fill_value)))
    data = x.ravel()[tuple(coords)]
    return cls(
        coords,
        data,
        shape=x.size,
        has_duplicates=False,
        sorted=True,
        fill_value=fill_value,
        idx_dtype=idx_dtype,
    ).reshape(x.shape)

todense()

将此sparse.COO数组转换为密集numpy.ndarray。请注意,如果COO对象的shape很大,这可能会占用大量内存。

返回

类型 描述
ndarray

转换后的密集数组。

另请参阅

示例

>>> x = np.random.randint(100, size=(7, 3))
>>> s = COO.from_numpy(x)
>>> x2 = s.todense()
>>> np.array_equal(x, x2)
True
源代码位于sparse/numba_backend/_coo/core.py
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
def todense(self):
    """
    Convert this [`sparse.COO`][] array to a dense [`numpy.ndarray`][]. Note that
    this may take a large amount of memory if the `COO` object's `shape`
    is large.

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

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

    Examples
    --------
    >>> x = np.random.randint(100, size=(7, 3))
    >>> s = COO.from_numpy(x)
    >>> x2 = s.todense()
    >>> np.array_equal(x, x2)
    True
    """
    x = np.full(self.shape, self.fill_value, self.dtype)

    coords = tuple([self.coords[i, :] for i in range(self.ndim)])
    data = self.data

    if len(coords) != 0:
        x[coords] = data
    else:
        if len(data) != 0:
            assert data.shape == (1,)
            x[...] = data[0]

    return x

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

scipy.sparse.spmatrix构建sparse.COO数组

参数

名称 类型 描述 默认值
x spmatrix

用于构建数组的稀疏矩阵。

必填
fill_value scalar

转换时使用的填充值。

返回

类型 描述
COO

转换后的sparse.COO对象。

示例

>>> import scipy.sparse
>>> x = scipy.sparse.rand(6, 3, density=0.2)
>>> s = COO.from_scipy_sparse(x)
>>> np.array_equal(x.todense(), s.todense())
True
源代码位于sparse/numba_backend/_coo/core.py
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
@classmethod
def from_scipy_sparse(cls, x, /, *, fill_value=None):
    """
    Construct a [`sparse.COO`][] array from a [`scipy.sparse.spmatrix`][]

    Parameters
    ----------
    x : scipy.sparse.spmatrix
        The sparse matrix to construct the array from.
    fill_value : scalar
        The fill-value to use when converting.

    Returns
    -------
    COO
        The converted [`sparse.COO`][] object.

    Examples
    --------
    >>> import scipy.sparse
    >>> x = scipy.sparse.rand(6, 3, density=0.2)
    >>> s = COO.from_scipy_sparse(x)
    >>> np.array_equal(x.todense(), s.todense())
    True
    """
    x = x.asformat("coo")
    if not x.has_canonical_format:
        x.eliminate_zeros()
        x.sum_duplicates()

    coords = np.empty((2, x.nnz), dtype=x.row.dtype)
    coords[0, :] = x.row
    coords[1, :] = x.col
    return COO(
        coords,
        x.data,
        shape=x.shape,
        has_duplicates=not x.has_canonical_format,
        sorted=x.has_canonical_format,
        fill_value=fill_value,
    )

from_iter(x, shape, fill_value=None, dtype=None) 类方法

将特定格式的可迭代对象转换为sparse.COO数组。详见示例。

参数

名称 类型 描述 默认值
x Iterable or Iterator

要转换为sparse.COO的可迭代对象。

必填
shape tuple[int]

数组的形状。

必填
fill_value scalar

此数组的填充值。

dtype dtype

输入数组的数据类型。如果未给定,则从输入推断。

返回

名称 类型 描述
输出 COO

输出sparse.COO数组。

示例

您可以转换sparse.COO格式的项。其中,第一部分表示坐标,第二部分表示值。

>>> x = [((0, 0), 1), ((1, 1), 1)]
>>> s = COO.from_iter(x, shape=(2, 2))
>>> s.todense()
array([[1, 0],
       [0, 1]])

您也可以使用字典实现类似格式。

>>> x = {(0, 0): 1, (1, 1): 1}
>>> s = COO.from_iter(x, shape=(2, 2))
>>> s.todense()
array([[1, 0],
       [0, 1]])

第三种支持的格式是(data, (..., row, col))

>>> x = ([1, 1], ([0, 1], [0, 1]))
>>> s = COO.from_iter(x, shape=(2, 2))
>>> s.todense()
array([[1, 0],
       [0, 1]])

您还可以传入一个collections.abc.Iterator对象。

>>> x = [((0, 0), 1), ((1, 1), 1)].__iter__()
>>> s = COO.from_iter(x, shape=(2, 2))
>>> s.todense()
array([[1, 0],
       [0, 1]])
源代码位于sparse/numba_backend/_coo/core.py
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
@classmethod
def from_iter(cls, x, shape, fill_value=None, dtype=None):
    """
    Converts an iterable in certain formats to a [`sparse.COO`][] array. See examples
    for details.

    Parameters
    ----------
    x : Iterable or Iterator
        The iterable to convert to [`sparse.COO`][].
    shape : tuple[int]
        The shape of the array.
    fill_value : scalar
        The fill value for this array.
    dtype : numpy.dtype
        The dtype of the input array. Inferred from the input if not given.

    Returns
    -------
    out : COO
        The output [`sparse.COO`][] array.

    Examples
    --------
    You can convert items of the format [`sparse.COO`][].
    Here, the first part represents the coordinate and the second part represents the value.

    >>> x = [((0, 0), 1), ((1, 1), 1)]
    >>> s = COO.from_iter(x, shape=(2, 2))
    >>> s.todense()
    array([[1, 0],
           [0, 1]])

    You can also have a similar format with a dictionary.

    >>> x = {(0, 0): 1, (1, 1): 1}
    >>> s = COO.from_iter(x, shape=(2, 2))
    >>> s.todense()
    array([[1, 0],
           [0, 1]])

    The third supported format is ``(data, (..., row, col))``.

    >>> x = ([1, 1], ([0, 1], [0, 1]))
    >>> s = COO.from_iter(x, shape=(2, 2))
    >>> s.todense()
    array([[1, 0],
           [0, 1]])

    You can also pass in a [`collections.abc.Iterator`][] object.

    >>> x = [((0, 0), 1), ((1, 1), 1)].__iter__()
    >>> s = COO.from_iter(x, shape=(2, 2))
    >>> s.todense()
    array([[1, 0],
           [0, 1]])
    """
    if isinstance(x, dict):
        x = list(x.items())

    if not isinstance(x, Sized):
        x = list(x)

    if len(x) != 2 and not all(len(item) == 2 for item in x):
        raise ValueError("Invalid iterable to convert to COO.")

    if not x:
        ndim = 0 if shape is None else len(shape)
        coords = np.empty((ndim, 0), dtype=np.uint8)
        data = np.empty((0,), dtype=dtype)
        shape = () if shape is None else shape

    elif not isinstance(x[0][0], Iterable):
        coords = np.stack(x[1], axis=0)
        data = np.asarray(x[0], dtype=dtype)
    else:
        coords = np.array([item[0] for item in x]).T
        data = np.array([item[1] for item in x], dtype=dtype)

    if not (
        coords.ndim == 2 and data.ndim == 1 and np.issubdtype(coords.dtype, np.integer) and np.all(coords >= 0)
    ):
        raise ValueError("Invalid iterable to convert to COO.")

    return COO(coords, data, shape=shape, fill_value=fill_value)

transpose(axes=None)

返回一个新数组,其轴的顺序已切换。

参数

名称 类型 描述 默认值
axes Iterable[int]

与之前相比的新轴顺序。默认反转轴。

返回

类型 描述
COO

轴以所需顺序排列的新数组。

另请参阅

示例

我们可以使用此函数更改任何sparse.COO数组的维度顺序。

>>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
>>> x
array([[4, 3, 2, 1, 0],
       [5, 4, 3, 2, 1],
       [6, 5, 4, 3, 2],
       [7, 6, 5, 4, 3],
       [8, 7, 6, 5, 4]])
>>> s = COO.from_numpy(x)
>>> s.transpose((1, 0)).todense()
array([[4, 5, 6, 7, 8],
       [3, 4, 5, 6, 7],
       [2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4]])

请注意,默认情况下,这会反转轴的顺序,而不是根据某些线性代数操作的要求切换倒数第二和倒数第一轴。

>>> x = np.random.rand(2, 3, 4)
>>> s = COO.from_numpy(x)
>>> s.transpose().shape
(4, 3, 2)
源代码位于sparse/numba_backend/_coo/core.py
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
def transpose(self, axes=None):
    """
    Returns a new array which has the order of the axes switched.

    Parameters
    ----------
    axes : Iterable[int], optional
        The new order of the axes compared to the previous one. Reverses the axes
        by default.

    Returns
    -------
    COO
        The new array with the axes in the desired order.

    See Also
    --------
    - [`sparse.COO.T`][] : A quick property to reverse the order of the axes.
    - [`numpy.ndarray.transpose`][] : Numpy equivalent function.

    Examples
    --------
    We can change the order of the dimensions of any [`sparse.COO`][] array with this
    function.

    >>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
    >>> x  # doctest: +NORMALIZE_WHITESPACE
    array([[4, 3, 2, 1, 0],
           [5, 4, 3, 2, 1],
           [6, 5, 4, 3, 2],
           [7, 6, 5, 4, 3],
           [8, 7, 6, 5, 4]])
    >>> s = COO.from_numpy(x)
    >>> s.transpose((1, 0)).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[4, 5, 6, 7, 8],
           [3, 4, 5, 6, 7],
           [2, 3, 4, 5, 6],
           [1, 2, 3, 4, 5],
           [0, 1, 2, 3, 4]])

    Note that by default, this reverses the order of the axes rather than switching
    the last and second-to-last axes as required by some linear algebra operations.

    >>> x = np.random.rand(2, 3, 4)
    >>> s = COO.from_numpy(x)
    >>> s.transpose().shape
    (4, 3, 2)
    """
    if axes is None:
        axes = list(reversed(range(self.ndim)))

    # Normalize all axes indices to positive values
    axes = normalize_axis(axes, self.ndim)

    if len(np.unique(axes)) < len(axes):
        raise ValueError("repeated axis in transpose")

    if not len(axes) == self.ndim:
        raise ValueError("axes don't match array")

    axes = tuple(axes)

    if axes == tuple(range(self.ndim)):
        return self

    if self._cache is not None:
        for ax, value in self._cache["transpose"]:
            if ax == axes:
                return value

    shape = tuple(self.shape[ax] for ax in axes)
    result = COO(
        self.coords[axes, :],
        self.data,
        shape,
        has_duplicates=False,
        cache=self._cache is not None,
        fill_value=self.fill_value,
    )

    if self._cache is not None:
        self._cache["transpose"].append((axes, result))
    return result

swapaxes(axis1, axis2)

返回轴axis1和axis2已交换的数组。

参数

名称 类型 描述 默认值
axis1 int

要交换的第一个轴

必填
axis2 int

要交换的第二个轴

必填

返回

类型 描述
COO

轴axis1和axis2已交换的新数组。

示例

>>> x = COO.from_numpy(np.ones((2, 3, 4)))
>>> x.swapaxes(0, 2)
<COO: shape=(4, 3, 2), dtype=float64, nnz=24, fill_value=0.0>
源代码位于sparse/numba_backend/_coo/core.py
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def swapaxes(self, axis1, axis2):
    """Returns array that has axes axis1 and axis2 swapped.

    Parameters
    ----------
    axis1 : int
        first axis to swap
    axis2 : int
        second axis to swap

    Returns
    -------
    COO
        The new array with the axes axis1 and axis2 swapped.

    Examples
    --------
    >>> x = COO.from_numpy(np.ones((2, 3, 4)))
    >>> x.swapaxes(0, 2)
    <COO: shape=(4, 3, 2), dtype=float64, nnz=24, fill_value=0.0>
    """
    # Normalize all axis1, axis2 to positive values
    axis1, axis2 = normalize_axis((axis1, axis2), self.ndim)  # checks if axis1,2 are in range + raises ValueError
    axes = list(range(self.ndim))
    axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
    return self.transpose(axes)

dot(other)

sparse.COO执行x.dot(y)的等效操作。

参数

名称 类型 描述 默认值
other Union[COO, ndarray, spmatrix]

点积操作的第二个操作数。

必填

返回

类型 描述
{COO, ndarray}

点积的结果。如果结果是密集数组,则返回密集数组;否则,返回稀疏数组。

引发

类型 描述
ValueError

如果所有参数都没有零填充值。

另请参阅

示例

>>> x = np.arange(4).reshape((2, 2))
>>> s = COO.from_numpy(x)
>>> s.dot(s)
array([[ 2,  3],
       [ 6, 11]], dtype=int64)
源代码位于sparse/numba_backend/_coo/core.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
951
952
953
954
955
956
957
958
959
960
def dot(self, other):
    """
    Performs the equivalent of `x.dot(y)` for [`sparse.COO`][].

    Parameters
    ----------
    other : Union[COO, numpy.ndarray, scipy.sparse.spmatrix]
        The second operand of the dot product operation.

    Returns
    -------
    {COO, numpy.ndarray}
        The result of the dot product. If the result turns out to be dense,
        then a dense array is returned, otherwise, a sparse array.

    Raises
    ------
    ValueError
        If all arguments don't have zero fill-values.

    See Also
    --------
    - [`sparse.dot`][] : Equivalent function for two arguments.
    - [`numpy.dot`][] : Numpy equivalent function.
    - [`scipy.sparse.coo_matrix.dot`][] : Scipy equivalent function.

    Examples
    --------
    >>> x = np.arange(4).reshape((2, 2))
    >>> s = COO.from_numpy(x)
    >>> s.dot(s)  # doctest: +SKIP
    array([[ 2,  3],
           [ 6, 11]], dtype=int64)
    """
    from .._common import dot

    return dot(self, other)

linear_loc()

此数组的展平版本的非零坐标。请注意,坐标可能无序。

返回

类型 描述
ndarray

展平后的坐标。

另请参阅

numpy.flatnonzero : 等效的Numpy函数。

示例

>>> x = np.eye(5)
>>> s = COO.from_numpy(x)
>>> s.linear_loc()
array([ 0,  6, 12, 18, 24])
>>> np.array_equal(np.flatnonzero(x), s.linear_loc())
True
源代码位于sparse/numba_backend/_coo/core.py
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def linear_loc(self):
    """
    The nonzero coordinates of a flattened version of this array. Note that
    the coordinates may be out of order.

    Returns
    -------
    numpy.ndarray
        The flattened coordinates.

    See Also
    --------
    [`numpy.flatnonzero`][] : Equivalent Numpy function.

    Examples
    --------
    >>> x = np.eye(5)
    >>> s = COO.from_numpy(x)
    >>> s.linear_loc()  # doctest: +NORMALIZE_WHITESPACE
    array([ 0,  6, 12, 18, 24])
    >>> np.array_equal(np.flatnonzero(x), s.linear_loc())
    True
    """
    from .common import linear_loc

    return linear_loc(self.coords, self.shape)

flatten(order='C')

返回一个新sparse.COO数组,它是此数组的展平版本。

返回

类型 描述
COO

展平后的输出数组。

注意

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

示例

>>> s = COO.from_numpy(np.arange(10))
>>> s2 = s.reshape((2, 5)).flatten()
>>> s2.todense()
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
源代码位于sparse/numba_backend/_coo/core.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def flatten(self, order="C"):
    """
    Returns a new [`sparse.COO`][] array that is a flattened version of this array.

    Returns
    -------
    COO
        The flattened output array.

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

    Examples
    --------
    >>> s = COO.from_numpy(np.arange(10))
    >>> s2 = s.reshape((2, 5)).flatten()
    >>> s2.todense()
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    """
    if order not in {"C", None}:
        raise NotImplementedError("The `order` parameter is notsupported.")

    return self.reshape(-1)

reshape(shape, order='C')

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

参数

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

输出数组的期望形状。

必填

返回

类型 描述
COO

重塑后的输出数组。

另请参阅

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

注意

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

示例

>>> s = COO.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/_coo/core.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
def reshape(self, shape, order="C"):
    """
    Returns a new [`sparse.COO`][] array that is a reshaped version of this array.

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

    Returns
    -------
    COO
        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 = COO.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]])
    """
    shape = tuple(shape) if isinstance(shape, Iterable) else (shape,)

    if order not in {"C", None}:
        raise NotImplementedError("The `order` parameter is not supported")

    if self.shape == shape:
        return self
    if any(d == -1 for d in shape):
        extra = int(self.size / np.prod([d for d in shape if d != -1]))
        shape = tuple([d if d != -1 else extra for d in shape])

    if self.size != reduce(operator.mul, shape, 1):
        raise ValueError(f"cannot reshape array of size {self.size} into shape {shape}")

    if self._cache is not None:
        for sh, value in self._cache["reshape"]:
            if sh == shape:
                return value

    # TODO: this self.size enforces a 2**64 limit to array size
    linear_loc = self.linear_loc()

    idx_dtype = self.coords.dtype
    if shape != () and not can_store(idx_dtype, max(shape)):
        idx_dtype = np.min_scalar_type(max(shape))
    coords = np.empty((len(shape), self.nnz), dtype=idx_dtype)
    strides = 1
    for i, d in enumerate(shape[::-1]):
        coords[-(i + 1), :] = (linear_loc // strides) % d
        strides *= d

    result = COO(
        coords,
        self.data,
        shape,
        has_duplicates=False,
        sorted=True,
        cache=self._cache is not None,
        fill_value=self.fill_value,
    )

    if self._cache is not None:
        self._cache["reshape"].append((shape, result))
    return result

squeeze(axis=None)

x中移除单例维度(轴)。

参数

名称 类型 描述 默认值
axis Union[None, int, Tuple[int, ...]]

要压缩的轴。如果指定轴的大小大于1,则引发ValueErroraxis=None移除所有单例维度。默认值:None

返回

类型 描述
COO

不含axis维度的输出数组。

示例

>>> s = COO.from_numpy(np.eye(2)).reshape((2, 1, 2, 1))
>>> s.squeeze().shape
(2, 2)
>>> s.squeeze(axis=1).shape
(2, 2, 1)
源代码位于sparse/numba_backend/_coo/core.py
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
def squeeze(self, axis=None):
    """
    Removes singleton dimensions (axes) from ``x``.
    Parameters
    ----------
    axis : Union[None, int, Tuple[int, ...]]
        The axis (or axes) to squeeze. If a specified axis has a size greater than one,
        a `ValueError` is raised. ``axis=None`` removes all singleton dimensions.
        Default: ``None``.
    Returns
    -------
    COO
        The output array without ``axis`` dimensions.
    Examples
    --------
    >>> s = COO.from_numpy(np.eye(2)).reshape((2, 1, 2, 1))
    >>> s.squeeze().shape
    (2, 2)
    >>> s.squeeze(axis=1).shape
    (2, 2, 1)
    """
    squeezable_dims = tuple([d for d in range(self.ndim) if self.shape[d] == 1])

    if axis is None:
        axis = squeezable_dims
    if isinstance(axis, int):
        axis = (axis,)
    elif isinstance(axis, Iterable):
        axis = tuple(axis)
    else:
        raise ValueError(f"Invalid axis parameter: `{axis}`.")

    for d in axis:
        if d not in squeezable_dims:
            raise ValueError(f"Specified axis `{d}` has a size greater than one: {self.shape[d]}")

    retained_dims = [d for d in range(self.ndim) if d not in axis]

    coords = self.coords[retained_dims, :]
    shape = tuple([s for idx, s in enumerate(self.shape) if idx in retained_dims])

    return COO(
        coords,
        self.data,
        shape,
        has_duplicates=False,
        sorted=True,
        cache=self._cache is not None,
        fill_value=self.fill_value,
    )

to_scipy_sparse(*, accept_fv=None)

将此sparse.COO对象转换为scipy.sparse.coo_matrix

参数

名称 类型 描述 默认值
accept_fv 标量或标量列表

接受的填充值列表。默认只接受零。

返回

类型 描述
coo_matrix

转换后的Scipy稀疏矩阵。

引发

类型 描述
ValueError

如果数组不是二维的。

ValueError

如果所有数组都没有零填充值。

另请参阅
源代码位于sparse/numba_backend/_coo/core.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
def to_scipy_sparse(self, /, *, accept_fv=None):
    """
    Converts this [`sparse.COO`][] object into a [`scipy.sparse.coo_matrix`][].

    Parameters
    ----------
    accept_fv : scalar or list of scalar, optional
        The list of accepted fill-values. The default accepts only zero.

    Returns
    -------
    scipy.sparse.coo_matrix
        The converted Scipy sparse matrix.

    Raises
    ------
    ValueError
        If the array is not two-dimensional.
    ValueError
        If all the array doesn't zero fill-values.

    See Also
    --------
    - [`sparse.COO.tocsr`][] : Convert to a [`scipy.sparse.csr_matrix`][].
    - [`sparse.COO.tocsc`][] : Convert to a [`scipy.sparse.csc_matrix`][].
    """
    import scipy.sparse

    check_fill_value(self, accept_fv=accept_fv)

    if self.ndim != 2:
        raise ValueError("Can only convert a 2-dimensional array to a Scipy sparse matrix.")

    result = scipy.sparse.coo_matrix((self.data, (self.coords[0], self.coords[1])), shape=self.shape)
    result.has_canonical_format = True
    return result

tocsr()

将此数组转换为scipy.sparse.csr_matrix

返回

类型 描述
csr_matrix

转换结果。

引发

类型 描述
ValueError

如果数组不是二维的。

ValueError

如果所有数组都没有零填充值。

另请参阅
源代码位于sparse/numba_backend/_coo/core.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def tocsr(self):
    """
    Converts this array to a [`scipy.sparse.csr_matrix`][].

    Returns
    -------
    scipy.sparse.csr_matrix
        The result of the conversion.

    Raises
    ------
    ValueError
        If the array is not two-dimensional.
    ValueError
        If all the array doesn't have zero fill-values.

    See Also
    --------
    - [`sparse.COO.tocsc`][] : Convert to a [`scipy.sparse.csc_matrix`][].
    - [`sparse.COO.to_scipy_sparse`][] : Convert to a [`scipy.sparse.coo_matrix`][].
    - [`scipy.sparse.coo_matrix.tocsr`][] : Equivalent Scipy function.
    """
    check_zero_fill_value(self)

    if self._cache is not None:
        try:
            return self._csr
        except AttributeError:
            pass
        try:
            self._csr = self._csc.tocsr()
            return self._csr
        except AttributeError:
            pass

        self._csr = csr = self._tocsr()
    else:
        csr = self._tocsr()
    return csr

tocsc()

将此数组转换为scipy.sparse.csc_matrix

返回

类型 描述
csc_matrix

转换结果。

引发

类型 描述
ValueError

如果数组不是二维的。

ValueError

如果数组没有零填充值。

另请参阅
源代码位于sparse/numba_backend/_coo/core.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
def tocsc(self):
    """
    Converts this array to a [`scipy.sparse.csc_matrix`][].

    Returns
    -------
    scipy.sparse.csc_matrix
        The result of the conversion.

    Raises
    ------
    ValueError
        If the array is not two-dimensional.
    ValueError
        If the array doesn't have zero fill-values.

    See Also
    --------
    - [`sparse.COO.tocsr`][] : Convert to a [`scipy.sparse.csr_matrix`][].
    - [`sparse.COO.to_scipy_sparse`][] : Convert to a [`scipy.sparse.coo_matrix`][].
    - [`scipy.sparse.coo_matrix.tocsc`][] : Equivalent Scipy function.
    """
    check_zero_fill_value(self)

    if self._cache is not None:
        try:
            return self._csc
        except AttributeError:
            pass
        try:
            self._csc = self._csr.tocsc()
            return self._csc
        except AttributeError:
            pass

        self._csc = csc = self.tocsr().tocsc()
    else:
        csc = self.tocsr().tocsc()

    return csc

broadcast_to(shape)

执行sparse.COO的等效操作。请注意,此函数返回一个新数组而不是视图。

参数

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

要广播数据的形状。

必填

返回

类型 描述
COO

广播后的稀疏数组。

引发

类型 描述
ValueError

如果操作数无法广播到给定形状。

另请参阅

numpy.broadcast_to : NumPy等效函数

源代码位于sparse/numba_backend/_coo/core.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def broadcast_to(self, shape):
    """
    Performs the equivalent of [`sparse.COO`][]. Note that
    this function returns a new array instead of a view.

    Parameters
    ----------
    shape : tuple[int]
        The shape to broadcast the data to.

    Returns
    -------
    COO
        The broadcasted sparse array.

    Raises
    ------
    ValueError
        If the operand cannot be broadcast to the given shape.

    See Also
    --------
    [`numpy.broadcast_to`][] : NumPy equivalent function
    """
    return broadcast_to(self, shape)

maybe_densify(max_size=1000, min_density=0.25)

如果成本不高,将此sparse.COO数组转换为numpy.ndarray

参数

名称 类型 描述 默认值
max_size int

输出中的最大元素数

1000
min_density float

输出的最小密度

0.25

返回

类型 描述
ndarray

密集数组。

引发

类型 描述
ValueError

如果返回的数组太大。

示例

将小型稀疏数组转换为密集数组。

>>> s = COO.from_numpy(np.random.rand(2, 3, 4))
>>> x = s.maybe_densify()
>>> np.allclose(x, s.todense())
True

您还可以指定允许的最小密度或最大输出元素数量。如果两个条件均未满足,此方法将抛出错误。

>>> x = np.zeros((5, 5), dtype=np.uint8)
>>> x[2, 2] = 1
>>> s = COO.from_numpy(x)
>>> s.maybe_densify(max_size=5, min_density=0.25)
Traceback (most recent call last):
    ...
ValueError: Operation would require converting large sparse array to dense
源代码位于sparse/numba_backend/_coo/core.py
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
def maybe_densify(self, max_size=1000, min_density=0.25):
    """
    Converts this [`sparse.COO`][] array to a [`numpy.ndarray`][] if not too
    costly.

    Parameters
    ----------
    max_size : int
        Maximum number of elements in output
    min_density : float
        Minimum density of output

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

    Raises
    ------
    ValueError
        If the returned array would be too large.

    Examples
    --------
    Convert a small sparse array to a dense array.

    >>> s = COO.from_numpy(np.random.rand(2, 3, 4))
    >>> x = s.maybe_densify()
    >>> np.allclose(x, s.todense())
    True

    You can also specify the minimum allowed density or the maximum number
    of output elements. If both conditions are unmet, this method will throw
    an error.

    >>> x = np.zeros((5, 5), dtype=np.uint8)
    >>> x[2, 2] = 1
    >>> s = COO.from_numpy(x)
    >>> s.maybe_densify(max_size=5, min_density=0.25)
    Traceback (most recent call last):
        ...
    ValueError: Operation would require converting large sparse array to dense
    """
    if self.size > max_size and self.density < min_density:
        raise ValueError("Operation would require converting large sparse array to dense")

    return self.todense()

nonzero()

获取此数组中非零元素的索引。

返回

名称 类型 描述
idx tuple[`numpy.ndarray`]

此数组中非零元素的索引。

另请参阅

numpy.ndarray.nonzero : NumPy等效函数

引发

类型 描述
ValueError

如果数组没有零填充值。

示例

>>> s = COO.from_numpy(np.eye(5))
>>> s.nonzero()
(array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))
源代码位于sparse/numba_backend/_coo/core.py
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
def nonzero(self):
    """
    Get the indices where this array is nonzero.

    Returns
    -------
    idx : tuple[`numpy.ndarray`]
        The indices where this array is nonzero.

    See Also
    --------
    [`numpy.ndarray.nonzero`][] : NumPy equivalent function

    Raises
    ------
    ValueError
        If the array doesn't have zero fill-values.

    Examples
    --------
    >>> s = COO.from_numpy(np.eye(5))
    >>> s.nonzero()
    (array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))
    """
    check_zero_fill_value(self)
    if self.ndim == 0:
        raise ValueError("`nonzero` is undefined for `self.ndim == 0`.")
    return tuple(self.coords)

asformat(format, **kwargs)

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

参数

名称 类型 描述 默认值
format str

格式字符串。

必填

返回

名称 类型 描述
输出 SparseArray

转换后的数组。

引发

类型 描述
NotImplementedError

如果不支持该格式。

源代码位于sparse/numba_backend/_coo/core.py
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
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 == "gcxs":
        from .._compressed import GCXS

        return GCXS.from_coo(self, **kwargs)

    if len(kwargs) != 0:
        raise TypeError(f"Invalid keyword arguments provided: {kwargs}")

    if format == "coo":
        return self

    if format == "dok":
        from .._dok import DOK

        return DOK.from_coo(self, **kwargs)

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

isinf()

测试数组的每个元素x_i,以确定其是否等于正无穷大或负无穷大。

源代码位于sparse/numba_backend/_coo/core.py
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
def isinf(self):
    """
    Tests each element ``x_i`` of the array to determine if equal to positive or negative infinity.
    """
    new_fill_value = bool(np.isinf(self.fill_value))
    new_data = np.isinf(self.data)

    return COO(
        self.coords,
        new_data,
        shape=self.shape,
        fill_value=new_fill_value,
        prune=True,
    )

isnan()

测试数组的每个元素x_i,以确定该元素是否为NaN

源代码位于sparse/numba_backend/_coo/core.py
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
def isnan(self):
    """
    Tests each element ``x_i`` of the array to determine whether the element is ``NaN``.
    """
    new_fill_value = bool(np.isnan(self.fill_value))
    new_data = np.isnan(self.data)

    return COO(
        self.coords,
        new_data,
        shape=self.shape,
        fill_value=new_fill_value,
        prune=True,
    )