使用python进行多元学生t分布

far*_*awa 5 python statistics scipy probability-density

要生成具有多元t分布的样本,请使用以下函数:

def multivariatet(mu,Sigma,N,M):
    '''
    Output:
    Produce M samples of d-dimensional multivariate t distribution
    Input:
    mu = mean (d dimensional numpy array or scalar)
    Sigma = scale matrix (dxd numpy array)
    N = degrees of freedom
    M = # of samples to produce
    '''
    d = len(Sigma)
    g = np.tile(np.random.gamma(N/2.,2./N,M),(d,1)).T
    Z = np.random.multivariate_normal(np.zeros(d),Sigma,M)
    return mu + Z/np.sqrt(g)
Run Code Online (Sandbox Code Playgroud)

但是我现在要寻找的是它本身的多元学生t分布,因此我可以计算出元素的密度dimension > 1

这将类似于scipystats.t.pdf(x, df, loc, scale)包,但在多维空间中。

far*_*awa 7

我自己编码了密度:

import numpy as np
from math import *

def multivariate_t_distribution(x,mu,Sigma,df,d):
    '''
    Multivariate t-student density:
    output:
        the density of the given element
    input:
        x = parameter (d dimensional numpy array or scalar)
        mu = mean (d dimensional numpy array or scalar)
        Sigma = scale matrix (dxd numpy array)
        df = degrees of freedom
        d: dimension
    '''
    Num = gamma(1. * (d+df)/2)
    Denom = ( gamma(1.*df/2) * pow(df*pi,1.*d/2) * pow(np.linalg.det(Sigma),1./2) * pow(1 + (1./df)*np.dot(np.dot((x - mu),np.linalg.inv(Sigma)), (x - mu)),1.* (d+df)/2))
    d = 1. * Num / Denom 
    return d
Run Code Online (Sandbox Code Playgroud)

  • 我注意到 Sigma 至少需要 2x2 的尺寸,否则 np.linalg 会呕吐。 (2认同)
  • 我没有解释为什么代码出现在其他地方,但我知道这个答案是在 2015 年写的,github 代码是在 2018 年推送的。也就是说,这里的 X 是你想要应用 t 分布的值 (2认同)