簡體   English   中英

Scipy CSR Matrix元素加法

[英]Scipy CSR Matrix Element-wise Addition

與numpy數組/矩陣不同,CSR矩陣似乎不允許自動廣播。 CSR實現中有一些方法可用於逐元素乘法,但不能添加。 如何有效地通過標量添加到CSR稀疏矩陣?

這里我們要為非零條目添加一個標量,並留下矩陣稀疏性,即不要觸摸零條目。


精細的Scipy文檔** emphasis **是我的):

 Attributes nnz Get the count of explicitly-stored values (nonzeros) has_sorted_indices Determine whether the matrix has sorted indices dtype (dtype) Data type of the matrix shape (2-tuple) Shape of the matrix ndim (int) Number of dimensions (this is always 2) **data CSR format data array of the matrix** indices CSR format index array of the matrix indptr CSR format index pointer array of the matrix 

所以我試過(第一部分是從被引用的文檔中“偷走”)

In [18]: from scipy import *

In [19]: from scipy.sparse import *

In [20]: row = array([0,0,1,2,2,2])
    ...: col = array([0,2,2,0,1,2])
    ...: data =array([1,2,3,4,5,6])
    ...: a = csr_matrix( (data,(row,col)), shape=(3,3))
    ...: 

In [21]: a.todense()
Out[21]: 
matrix([[1, 0, 2],
        [0, 0, 3],
        [4, 5, 6]], dtype=int64)

In [22]: a.data += 10

In [23]: a.todense()
Out[23]: 
matrix([[11,  0, 12],
        [ 0,  0, 13],
        [14, 15, 16]], dtype=int64)

In [24]: 

有用。 如果保存原始矩陣,可以使用修改后的數據數組使用構造函數。


放棄

這個答案解決了這個問題的解釋

我有一個稀疏矩陣,我想在非零項中添加一個標量,保留矩陣及其程序表示的稀疏性

我選擇這種解釋的原因是為所有條目添加標量會使稀疏矩陣變為非常密集的矩陣......

如果這是正確的解釋,我不知道:一方面,OP在我們的問題下面的評論中批准了我的答案(至少在2017-07-13),但似乎他們有不同的意見。

然而,答案在稀疏矩陣表示的用例中很有用,例如,稀疏測量並且您想要校正測量偏差,減去平均值等等所以我將把它留在這里,即使它可以判斷有爭議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM