[英]Normalize 2d arrays
Consider a square matrix containing positive numbers, given as a 2d numpy array A of shape ((m,m)). 考虑一个包含正数的方阵,给出为形状为((m,m))的2d numpy数组A。 I would like to build a new array B that has the same shape with entries
我想建立一个与条目具有相同形状的新数组B
B[i,j] = A[i,j] / (np.sqrt(A[i,i]) * np.sqrt(A[j,j]))
An obvious solution is to loop over all (i,j) but I'm wondering if there is a faster way. 一个明显的解决方案是遍历所有(i,j),但我想知道是否有更快的方法。
Two approaches leveraging broadcasting
could be suggested. 可以提出两种利用
broadcasting
方法。
Approach #1 : 方法1:
d = np.sqrt(np.diag(A))
B = A/d[:,None]
B /= d
Approach #2 : 方法2:
B = A/(d[:,None]*d) # d same as used in Approach #1
Approach #1 has lesser memory overhead and as such I think would be faster. 方法1具有较少的内存开销,因此我认为这样会更快。
You can normalize each row of your array by the main diagonal leveraging broadcasting using 您可以利用主对角线利用
b = np.sqrt(np.diag(a))
a / b[:, None]
Also, you can normalize each column using 另外,您可以使用
a / b[None, :]
To do both, as your question seems to ask, using 正如您的问题所要求的,同时使用
a / (b[:, None] * b[None, :])
If you want to prevent the creation of intermediate arrays and do the operation in place, you can use 如果要防止创建中间数组并执行适当的操作,则可以使用
a /= b[:, None]
a /= b[None, :]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.