简体   繁体   English

numpy-逐行标准化

[英]Numpy - row-wise normalization

I've been working on a matrix normalization problem, stated as: 我一直在研究矩阵归一化问题,表示为:

Given a matrix M, normalize its elements such that each element is divided with the corresponding column sum if element is not 0. 给定矩阵M,对其元素进行归一化,使得如果element不为0,则将每个元素除以相应的列总和。

cwsums = np.sum(class_matrix,axis=1)
cwsums = np.reciprocal(cwsums.astype(np.float32))
cwsums[cwsums == np.inf] = 0
## this is the problem
final_matrix = np.multiply(final_matrix, cwsums)

I can construct a reciprocal mask, which I would like to apply accross the matrix, as an elementwise product, yet I can't seem to get it right. 我可以构造一个互易蒙版,将其作为元素产品应用于整个矩阵,但似乎无法正确处理。 Thank you! 谢谢!

(Addressing edited question) Looks like you meant to sum across rows using axis=0 : (解决已编辑的问题)您似乎打算使用axis=0对各行求和:

i = 1 / class_matrix.sum(axis=0)
i[~np.isfinite(i)] = 0

class_matrix *= i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM