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)
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])
r_inv[np.isinf(r_inv)] = 0. 如果r_inv存在inf(无穷)时赋值为0
r_mat_inv = sp.diags(r_inv)就是用r_inv的值构造一个对角矩阵
.dot用法可以参考下:
.(4条消息) np.dot()使用方法_pillstap的博客-CSDN博客_np.dot
print(mx):
print(a):
print(a.A):
format
mx: csr_matrix
a:coo_matrix