Replace looping-over-axes with broadcasting

痴心易碎 提交于 2019-12-11 05:35:12

问题


Say I have:

a = np.array([[2, 4],
              [6, 8]])    
b = np.array([[1, 3],
              [1, 5]])

I want to get to:

c = np.array([[20,32],
              [28, 44]])

where c is the result of multiplying each column of a by b, then summing that result along the first axis.

I.e.:

print(np.sum(a[:, 0] * b, axis=1))
[20 32]

print(np.sum(a[:, 1] * b, axis=1))
[28 44]

Can I do through broadcasting rather than:

  • using np.apply_along_axis or
  • looping through each column?

回答1:


You can use np.dot -

b.dot(a).T

Alternatively, using np.einsum (for the kicks maybe) -

np.einsum('ij,ki->jk',a,b)


来源:https://stackoverflow.com/questions/45200611/replace-looping-over-axes-with-broadcasting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!