[英]Numpy matrix operations
I want to compute the following values for all i
and j
: 我想为所有
i
和j
计算以下值:
M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n]
How can I do it using Numpy (Python) without an explicit loop? 如何在没有显式循环的情况下使用Numpy(Python)来完成它?
Thanks! 谢谢!
Here is a general strategy for solving this kind of problem. 这是解决此类问题的一般策略。
First, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same: 首先,编写一个小脚本,将循环显式写入两个不同的函数,最后进行测试,确保两个函数完全相同:
import numpy as np
from numpy import newaxis
def explicit(a):
n = a.shape[0]
m = np.zeros_like(a)
for k in range(n):
for i in range(n):
for j in range(n):
m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k]
return m
def implicit(a):
n = a.shape[0]
m = np.zeros_like(a)
for k in range(n):
for i in range(n):
for j in range(n):
m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k]
return m
a = np.random.randn(10,10)
assert np.allclose(explicit(a), implicit(a), atol=1e-10, rtol=0.)
Then, vectorize the function step by step by editing implicit
, running the script at each step to make sure that they continue staying the same: 然后,通过编辑
implicit
来逐步向量化函数,在每一步运行脚本以确保它们继续保持不变:
Step 1 第1步
def implicit(a):
n = a.shape[0]
m = np.zeros_like(a)
for k in range(n):
for i in range(n):
m[k,i] = (a[i,:] - a[k,:]).sum() - n*a[i,k] + n*a[k,k]
return m
Step 2 第2步
def implicit(a):
n = a.shape[0]
m = np.zeros_like(a)
m = - n*a.T + n*np.diag(a)[:,newaxis]
for k in range(n):
for i in range(n):
m[k,i] += (a[i,:] - a[k,:]).sum()
return m
Step 3 第3步
def implicit(a):
n = a.shape[0]
m = np.zeros_like(a)
m = - n*a.T + n*np.diag(a)[:,newaxis]
m += (a.T[newaxis,...] - a[...,newaxis]).sum(1)
return m
Et voila'! 瞧瞧'! No loops in the last one.
最后一个没有循环。 To vectorize that kind of equations, broadcasting is the way to go!
为了矢量化这种方程式, 广播是要走的路!
Warning: make sure that explicit
is the equation that you wanted to vectorize. 警告:确保
explicit
是您想要向量化的等式。 I wasn't sure if the terms that do not depend on j
should also be summed over. 我不确定是否也应该总结不依赖于
j
的术语。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.