Row-normalize sparse matrix

import numpy as np
import scipy.sparse as sp
import torch

def normalize_row(mx):
    """Row-normalize sparse matrix"""
    rowsum = np.array(mx.sum(1))
    r_inv = np.power(rowsum, -1).flatten()
    r_inv[np.isinf(r_inv)] = 0.
    r_mat_inv = sp.diags(r_inv)
    mx = r_mat_inv.dot(mx)
    return mx.tocoo()

mx = sp.csr_matrix([[0,1,0,1],[0,0,0,1],[1,0,0,1],[0,1,0,0]])
a=normalize_row(mx)

Row-normalize sparse matrix_第1张图片

rowsum = np.array(mx.sum(1)) #矩阵行求和  [[2],[1],[2],[1]]

运行到r_inv = np.power(rowsum, -1).flatten()出错了

ValueError: Integers to negative integer powers are not allowed.

rowsum的数据类型是整数,不是浮点数,只有浮点数才能进行power运算

于是我加了个小数点  mx = sp.csr_matrix([[0.0,1,0,1],[0,0,0,1],[1,0,0,1],[0,1,0,0]])

flatten()相当于flatten(0)

举个栗子 a的维度是(2,2),a这个数据从0维展开,就是(2 ∗ 2=4),维度就是(6)

a : tensor([[0.2,0.3],[0.5,0.6]])

a.flatten() : tensor([0.2,0.3,0.5,0.6])

Row-normalize sparse matrix_第2张图片

r_inv[np.isinf(r_inv)] = 0.

如果r_inv存在inf(无穷)时赋值为0

  r_mat_inv = sp.diags(r_inv)就是用r_inv的值构造一个对角矩阵

Row-normalize sparse matrix_第3张图片

.dot用法可以参考下:

.​​(4条消息) np.dot()使用方法_pillstap的博客-CSDN博客_np.dot

print(mx):

Row-normalize sparse matrix_第4张图片

print(a):

Row-normalize sparse matrix_第5张图片

print(a.A):

Row-normalize sparse matrix_第6张图片

format

mx: csr_matrix

a:coo_matrix

你可能感兴趣的:(numpy,python)