从两个 Numpy 数组高效生成柯西矩阵

lee*_*ewz 3 python optimization numpy matrix

柯西矩阵(维基百科文章)是由两个向量(数字数组)确定的矩阵。给定两个向量xy,由它们生成的柯西矩阵C按条目定义为

C[i][j] := 1/(x[i] - y[j])
Run Code Online (Sandbox Code Playgroud)

给定两个 Numpy 数组xy,生成柯西矩阵的有效方法是什么?

lee*_*ewz 6

这是我发现的最有效的方法,使用数组广播来利用矢量化。

1.0 / (x.reshape((-1,1)) - y)
Run Code Online (Sandbox Code Playgroud)

编辑:@HYRY 和 @shx2 建议您可以使用返回同一数组的视图,而不是x.reshape((-1,1))创建副本。x[:,np.newaxis]@HYRY 还建议1.0/np.subtract.outer(x,y),这对我来说稍微慢一些,但可能更明确。


例子:

>>> x = numpy.array([1,2,3,4]) #x
>>> y = numpy.array([5,6,7])   #y
>>>
>>> #transpose x, to nx1
... x = x.reshape((-1,1))
>>> x
array([[1],
       [2],
       [3],
       [4]])
>>>
>>> #array of differences x[i] - y[j]
... #an nx1 array minus a 1xm array is an nxm array
... diff_matrix = x-y
>>> diff_matrix
array([[-4, -5, -6],
       [-3, -4, -5],
       [-2, -3, -4],
       [-1, -2, -3]])
>>>
>>> #apply the multiplicative inverse to each entry
... cauchym = 1.0/diff_matrix
>>> cauchym
array([[-0.25      , -0.2       , -0.16666667],
       [-0.33333333, -0.25      , -0.2       ],
       [-0.5       , -0.33333333, -0.25      ],
       [-1.        , -0.5       , -0.33333333]])
Run Code Online (Sandbox Code Playgroud)

我尝试了一些其他方法,所有这些方法都明显慢了。

这是一种幼稚的方法,需要列表理解:

cauchym = numpy.array([[ 1.0/(x_i-y_j) for y_j in y] for x_i in x])
Run Code Online (Sandbox Code Playgroud)

这会将矩阵生成为一维数组(节省嵌套 Python 列表的成本),然后将其重新整形为矩阵。它还将除法移动到单个 Numpy 运算:

cauchym = 1.0/numpy.array([(x_i-y_j) for x_i in x for y_j in y]).reshape([len(x),len(y)])
Run Code Online (Sandbox Code Playgroud)

使用numpy.repeatnumpy.tile(分别水平和垂直平铺数组)。这种方式会产生不必要的副本:

lenx = len(x)
leny = len(y)
xm = numpy.repeat(x,leny) #the i'th row is s_i
ym = numpy.tile(y,lenx)
cauchym = (1.0/(xm-ym)).reshape([lenx,leny]);
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用:`1.0/np.subtract.outer(x, y)`、`1.0/(x[:,None]-y)` (2认同)