python Scipy使用稀疏阵列与信号,相关

8mmmxcuj  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(162)

我尝试在Scipy中使用稀疏矩阵计算序列相关性,得到一个错误,我的数组没有相同的维度,但它们看起来是相同的。示例代码:

  1. import numpy
  2. import scipy.signal as signal
  3. import scipy.sparse as sparse
  4. my_sparse = sparse.csr_array(numpy.random.rand(10))
  5. print(my_sparse)
  6. print(my_sparse.shape)
  7. my_dense = numpy.expand_dims(numpy.random.rand(10), 1).T
  8. print(my_dense)
  9. print(my_dense.shape)
  10. corr = signal.correlate(my_sparse, my_dense, method="direct", mode="full")
  11. print(corr)
  12. print(corr.shape)

字符串
产出:

  1. $ python test_sparse_with_correlate.py
  2. (0, 0) 0.9842628978990572
  3. (0, 1) 0.21288927130505086
  4. (0, 2) 0.11321754428562536
  5. (0, 3) 0.02907902961562403
  6. (0, 4) 0.06534326022150638
  7. (0, 5) 0.5611332833785263
  8. (0, 6) 0.6693945587792903
  9. (0, 7) 0.6421603953803423
  10. (0, 8) 0.7299602339571223
  11. (0, 9) 0.5241172106721759
  12. (1, 10)
  13. [[0.5422929 0.27431614 0.65966523 0.05579376 0.41876797 0.46535913
  14. 0.13079666 0.97518169 0.49505634 0.68287069]]
  15. (1, 10)
  16. Traceback (most recent call last):
  17. File "/mnt/alt_wkdir/118_serial_correlation/code/test_sparse_with_correlate.py", line 13, in <module>
  18. corr = signal.correlate(my_sparse, my_dense, method="direct", mode="full")
  19. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  20. File "/mnt/bioinf_tools/miniconda3/envs/scipy/lib/python3.12/site-packages/scipy/signal/_signaltools.py", line 231, in correlate
  21. raise ValueError("in1 and in2 should have the same dimensionality")
  22. ValueError: in1 and in2 should have the same dimensionality


我也尝试过用数组的转置版本(所以它们的形状都是(10,1)),结果是相同的ValueError。
我使用的是scipy的v1.11.4,我首先发现了旧版本的问题,用最新的稳定版scipy创建了一个新的conda环境,看到了同样的行为。
是否可以将scipy.sparse与scipy.signal.correlate一起使用,如果可以,您能告诉我如何使用吗?

tzcvj98z

tzcvj98z1#

创建密集和稀疏(1,10)数组:

  1. In [85]: arr = np.random.rand(1,10); sarr = sparse.csr_matrix(arr)
  2. In [86]: arr
  3. Out[86]:
  4. array([[0.45548693, 0.13739717, 0.01448538, 0.06410341, 0.593232 ,
  5. 0.53930553, 0.54963769, 0.39025394, 0.71102781, 0.83568432]])
  6. In [87]: sarr
  7. Out[87]:
  8. <1x10 sparse matrix of type '<class 'numpy.float64'>'
  9. with 10 stored elements in Compressed Sparse Row format>

字符串
正如我在评论中提到的,你的correlate试图将其参数转换为密集数组。对于稀疏数组,结果是:

  1. In [88]: np.asarray(sarr)
  2. Out[88]:
  3. array(<1x10 sparse matrix of type '<class 'numpy.float64'>'
  4. with 10 stored elements in Compressed Sparse Row format>, dtype=object)


这只是将稀疏对象 Package 在0d个对象dtype数组中:

  1. In [90]: np.asarray(sarr).shape
  2. Out[90]: ()


所以很明显维度不同。
我认为稀疏文档警告说,在通用的numpy代码中使用稀疏矩阵通常不起作用。numpy不知道sparse
制作密集数组的正确方法是使用矩阵自己的方法:

  1. In [92]: sarr.toarray()
  2. Out[92]:
  3. array([[0.45548693, 0.13739717, 0.01448538, 0.06410341, 0.593232 ,
  4. 0.53930553, 0.54963769, 0.39025394, 0.71102781, 0.83568432]])

展开查看全部

相关问题