用PyMC3优化

2024-04-25 16:58:21 发布

您现在位置:Python中文网/ 问答频道 /正文

问题摘要

我一直在优化我的函数VectorizedVcdfe,我仍在尝试优化它。此函数负责另一个函数customFunc99%的慢度。这个customFunc用于PyMC3代码块。你知道吗

请帮我优化VectorizedVcdfe。你知道吗

优化函数

def VectorizedVcdfe(self, x, dataVector, recip_h_times_lambda_vector):
    n = len(dataVector)

    differenceVector = x - dataVector

    stackedDiffVecAndRecipVec = pymc3.math.stack(differenceVector, recip_h_times_lambda_vector)

    erfcTerm  = 1. - pymc3.math.erf(self.neg_sqrt1_2 * pymc3.math.prod(stackedDiffVecAndRecipVec, axis=0))

    # Calc F_Hat
    F_Hat = (1. / float(n)) * pymc3.math.sum(0.5 * erfcTerm)

    # Return F_Hat
    return(F_Hat)

参数/变量

x是张量变量。你知道吗

dataVector是一个1Xn numpy矩阵。你知道吗

recip_h_times_lambda_vector也是一个1Xn numpy矩阵。你知道吗

neg_sqrt1_2是一个标量常量。你知道吗

如何使用customFunc

with pymc3.Model() as model:
    # Create likelihood
    like = pymc3.DensityDist('X', customFunc, shape=2)

    # Make samples
    step = pymc3.NUTS()
    trace = pymc3.sample(2000, tune=1000, init=None, step=step, cores=2)

编辑:

为了回答评论,随机值对于dataVectorrecip_h_times_lambda_vector进行优化。实际上,recip_h_times_lambda_vector依赖于dataVector和标量参数h。你知道吗

一些评论者想知道customFunc,所以这里是。。。你知道吗

def customFunc(X):
    Y = []
    for j in range(2):
        x_j = X[j]
        F_x_j = fittedKdEstimator.VCDFE(x_j)
        y_j = myPPF(F_x_j)
        Y.append(y_j)

    logLikelihood = 0.
    recipSqrtTwoPi = 1. / math.sqrt(2. * math.pi)

    for j in range(2):
        y_j = Y[j]
        logLikelihood += pymc3.math.log(recipSqrtTwoPi * pymc3.math.exp(y_j * y_j / -2.))

    return(pymc3.math.exp(logLikelihood))

全局变量fittedKdEstimator是包含函数VectorizedVcdfeVCDFE的类的实例。你知道吗

下面是VCDFE的Python代码。。。你知道吗

def VCDFE(self, x):
    if not self.beenFit: raise Exception("Must first fit to data")

    return(self.VectorizedVcdfe(x, self.__dataVector, self.__recip_h_times_lambda_vector))

另一方面,函数myPPF是我实现的标准正规“百分位函数”(AKA:“分位数函数”)。我已经对customFunc进行了计时,myPPF占用了整个时间的一小部分。绝大多数时间被VectorizedVcdfe消耗。你知道吗

最后但并非最不重要的是,n的典型值可能在10000到100000之间。你知道吗


Tags: lambda函数selfreturnhatdefmathvector