开发者

In SciPy, fancy indexing for csr_matrices

I am new to Python, so forgive me ahead of time if this is an elementary question, but I have searched around and have not found a satisfying answer.

I am trying to do the following using NumPy and SciPy:

I,J = x[:,0], x[:1]               # x is a two column array of (r,c) pairs
V = ones(len(I))
G = sparse.coo_matrix((V,(I,J)))  # G's dimensions are 1032570x1032570
G = G + transpose(G)
r,c = G.nonzero()
G[r,c] = 1
...
NotImplementedError: Fancy indexing in assignment not supported for csr matrices

Pretty much, I want all the nonzero values to equal 1 after adding the transpose, but I get the fancy indexing error messages.

Alternatively, if I could show that the matrix G is symmetric, adding the transpose woul开发者_运维技巧d not be necessary.

Any insight into either approach would be very much appreciated.


In addition to doing something like G = G / G, you can operate on G.data.

So, in your case, doing either:

G.data  = np.ones(G.nnz)

or

G.data[G.data != 0] = 1

Will do what you want. This is more flexible, as it allows you to preform other types of filters (e.g. G.data[G.data > 0.9] = 1 or G.data = np.random.random(G.nnz))

The second option will only set the values to one if they have a nonzero value. During some calculations, you'll wind up with zero values that are "dense" (i.e. they're actually stored as a value in the sparse array). (You can remove these in-place with G.eliminate_zeros())

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜