使用 numpy einsum 计算矩阵列向量的内积 [英] Using numpy einsum to compute inner product of column-vectors of a matrix
本文介绍了使用 numpy einsum 计算矩阵列向量的内积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个像这样的 numpy 矩阵:
Suppose I have a numpy matrix like this:
[[ 1 2 3]
[ 10 100 1000]]
我想计算每列与其自身的内积,所以结果是:
I would like to compute the inner product of each column with itself, so the result would be:
[1*1 + 10*10 2*2 + 100*100 3*3 + 1000*1000] == [101, 10004, 1000009]
我想知道是否可以使用 einsum
函数(并更好地理解它).
I would like to know if this is possible using the einsum
function (and to better understand it).
到目前为止,我能得到的最接近的结果是:
So far, the closest result I could have is:
import numpy as np
arr = np.array([[1, 2, 3], [10, 100, 1000]])
res = np.einsum('ij,ik->jk', arr, arr)
# [[ 101 1002 10003]
# [ 1002 10004 100006]
# [ 10003 100006 1000009]]
对角线包含预期结果,但我想知道是否可以避免边缘计算.
The diagonal contains the expected result, but I would like to know if I can avoid edge calculations.
推荐答案
使用 np.einsum
,就像这样 -
Use np.einsum
, like so -
np.einsum('ij,ij->j',arr,arr)
样品运行 -
In [243]: np.einsum('ij,ij->j',arr,arr)
Out[243]: array([ 101, 10004, 1000009])
或者用 np.sum
-
In [244]: (arr**2).sum(0)
Out[244]: array([ 101, 10004, 1000009])
或者使用 numexpr
模块 -
Or with numexpr
module -
In [248]: import numexpr as ne
In [249]: ne.evaluate('sum(arr**2,0)')
Out[249]: array([ 101, 10004, 1000009])
这篇关于使用 numpy einsum 计算矩阵列向量的内积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文