我大概要转换这个(非numpy的)for循环:
N = len(left)
M = len(right)
matrix = np.zeros(N, M)
for i in range(N):
for j in range(M):
matrix[i][j] = scipy.stats.binom.pmf(left[i], C, right[j])
有点像点积,但从数学上来说当然不是点积。我通常如何矢量化或制作类似pythonic / numpythonic的东西?
答案 0 :(得分:3)
scipy.stats.binom.pmf
已被矢量化。但是,您必须 broadcast
以获得您想要的结果。
broadcast_out = scipy.stats.binom.pmf(left[:, None], C, right)
验证
np.random.seed(314)
left = np.arange(5, dtype=float)
right = np.random.rand(5)
C = 5
broadcast_out = scipy.stats.binom.pmf(left[:, None], C, right)
N = len(left)
M = len(right)
matrix = np.zeros((N, M))
for i in range(N):
for j in range(M):
matrix[i][j] = scipy.stats.binom.pmf(left[i], C, right[j])
print(np.array_equal(matrix, broadcast_out))
True