Using numpy einsum to compute inner product of column-vectors of a matrix

断了今生、忘了曾经 提交于 2019-12-01 23:08:16

Use np.einsum, like so -

np.einsum('ij,ij->j',arr,arr)

Sample run -

In [243]: np.einsum('ij,ij->j',arr,arr)
Out[243]: array([    101,   10004, 1000009])

Or with np.sum -

In [244]: (arr**2).sum(0)
Out[244]: array([    101,   10004, 1000009])

Or with numexpr module -

In [248]: import numexpr as ne

In [249]: ne.evaluate('sum(arr**2,0)')
Out[249]: array([    101,   10004, 1000009])

What you're expecting here can be understood intuitively, with one intermediate step from Divakar's einsum answer.

In [19]: arr
Out[19]: 
array([[   1,    2,    3],
       [  10,  100, 1000]])

# simply take element-wise product with the array itself
In [20]: np.einsum('ij, ij -> ij', arr, arr)
Out[20]: 
array([[      1,       4,       9],
       [    100,   10000, 1000000]])

But, this doesn't give the result that you expected. So, if you observe the above result, we just need to sum along the first dimension (i.e. axis 0). So, we omit the subscript i after -> in the einsum result, which means we ask it to sum along that axis, and that yields the expected result which is:

In [21]: np.einsum('ij, ij -> j', arr, arr)
Out[21]: array([    101,   10004, 1000009])

P.S. Also, for a general understanding of np.einsum, see the detailed discussion here: understanding-numpy-einsum

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