【问题标题】:How to take advantage of vectorization when computing the pdf for a multivariate gaussian?在计算多元高斯的pdf时如何利用矢量化?
【发布时间】:2021-01-18 14:55:55
【问题描述】:

我花了几个小时在谷歌上搜索这个问题,似乎找不到任何信息。

我尝试将多元高斯 pdf 编码为:

def multivariate_normal(X, M, S):

    # X has shape (D, N) where D is the number of dimensions and N the number of observations
    # M is the mean vector with shape (D, 1)
    # S is the covariance matrix with shape (D, D)

    D = S.shape[0]
    S_inv = np.linalg.inv(S)
    logdet = np.log(np.linalg.det(S))
    log2pi = np.log(2*np.pi)
    devs = X - M

    a = np.array([- D/2 * log2pi - (1/2) * logdet - dev.T @ S_inv @ dev for dev in devs.T])

return np.exp(a)

我只通过for循环成功地计算了pdf,迭代了N次。如果我不这样做,我最终会得到一个无用的 (N, N) 矩阵。我找到了另一个帖子here,但该帖子已经过时并且在matlab中。

有没有办法利用 numpy 的向量化?

这是我在 stackoverflow 上的第一篇文章,如果有什么问题请告诉我!d

【问题讨论】:

    标签: python numpy vectorization gaussian


    【解决方案1】:

    我以类似的方式遇到了这个问题,我是这样解决的:

    变量:

    • X = numpy.ndarray[numpy.ndarray[float]] - m x n
    • MU = numpy.ndarray[numpy.ndarray[float]] - k x n
    • SIGMA = numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]] - k x n x n
    • k = int

    X 是我的特征向量,MU 是我的均值,SIGMA 是我的协方差矩阵。

    为了矢量化,我根据点积的定义重写了点积:

    sigma_det = np.linalg.det(sigma)
    sigma_inv = np.linalg.inv(sigma)
    const = 1/((2*np.pi)**(n/2)*sigma_det**(1/2))
    p = const*np.exp((-1/2)*np.sum((X-mu).dot(sigma_inv)*(X-mu),axis=1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-09
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 2018-01-30
      相关资源
      最近更新 更多