简体   繁体   English

为2D numpy数组形成协方差矩阵

[英]Forming a Co-variance matrix for a 2D numpy array

I am trying to figure out a fully vectorised way to compute the co-variance matrix for a 2D numpy array for a given base kernel function. 我试图找出一种完全矢量化的方法,以便为给定的基本内核函数计算2D numpy数组的协方差矩阵。 For example if the input is X = [[a,b],[c,d]] for a kernel function k(x_1,x_2) the covariance matrix will be 例如,如果输入为内核函数k(x_1,x_2)X = [[a,b],[c,d]] ,则协方差矩阵为

K=[[k(a,a),k(a,b),k(a,c),k(a,d)], [k(b,a),k(b,b),k(b,c),k(b,d)], [k(c,a),k(c,b),k(c,c),k(c,d)], [k(d,a),k(d,b),k(d,c),k(d,d)]] . K=[[k(a,a),k(a,b),k(a,c),k(a,d)], [k(b,a),k(b,b),k(b,c),k(b,d)], [k(c,a),k(c,b),k(c,c),k(c,d)], [k(d,a),k(d,b),k(d,c),k(d,d)]]

how do I go about doing this? 我该怎么做呢? I am confused as to how to repeat the values and then apply the function and what might be the most efficient way of doing this. 我对如何重复这些值然后应用该函数以及执行此操作的最有效方法感到困惑。

You can use np.meshgrid to get two matrices with values for the first and second parameter to the k function. 您可以使用np.meshgrid来获得两个矩阵,两个矩阵的值分别为k函数的第一个和第二个参数。

In [8]: X = np.arange(4).reshape(2,2)    
In [9]: np.meshgrid(X, X)
Out[9]: 
[array([[0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3]]), 
 array([[0, 0, 0, 0],
        [1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]])]

You can then just pass these matrices to the k function: 然后,您可以将这些矩阵传递给k函数:

In [10]: k = lambda x1, x2: (x1-x2)**2

In [11]: X1, X2 = np.meshgrid(X, X)

In [12]: k(X1, X2)
Out[12]: 
array([[0, 1, 4, 9],
       [1, 0, 1, 4],
       [4, 1, 0, 1],
       [9, 4, 1, 0]])

这是另一种方式

k(X.reshape(-1, 1), X.reshape(1, -1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM