Python将整个列表与高斯分布相结合

2024-10-01 11:25:59 发布

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

我试着画出这个正态分布的积分,对于大于x的值,定义为

enter image description here

在哪里

enter image description here

在python中定义这两个函数

import scipy.integrate as integrate
import numpy as np

def gaussian(x, mu, sig):
    norm = 1/np.sqrt(2*np.pi*sig*sig)
    return norm * np.exp(-np.power(x - mu, 2.) / (2. * sig*sig))

def gaussianGreater(x, mu, sig):
    Integrand = lambda x: gaussian(x, mu, sig)
    return integrate.quad(Integrand,-np.Inf, x)[0]

我现在的问题在于我的gaussianGreater函数在通过分布函数求值时的积分边界。在评估时,会发生这种情况。在

^{pr2}$

我尝试将上限更改为错误给出的值,但这将返回错误'float' object has no attribute '__getitem__'

应用for循环也不起作用

[gaussianGreater(x, mu_1, sig_1 ) for x in subdist_1]

TypeError: only integer arrays with one element can be converted to an index

我如何解决这个问题?在


Tags: 函数importnormreturn定义defas错误
2条回答

对于1-F(x),可以直接使用scipy.stats.norm的生存函数:

import scipy.stats as ss
x = np.linspace(-3, 3, 100)
y = ss.norm.sf(x)  # you can pass its mean and std. dev. as well
plt.plot(x, y)

enter image description here

只有当x是一个float时,您所定义的才有效。如果您想要的是能够传递一个numpy数组,比如np.array([0.2, 0.3])并得到[N(gt;0.2),N(gt;0.3)],那么您可以使用已经定义的函数,只需调用vectorize方法。因此,如果a是您正在使用的numpy数组,a.vectorize(gaussianGreater)会给您一个对每个元素应用gaussianGreater的数组。您可以定义另一个函数vectorGausssianGreater,它接受一个数组,并返回对它的向量化调用的结果。如果您真正想要的是一个可以接受数组值的函数,可以定义如下内容:

def gaussian_greater(values, mean, standard_deviation):
    def greater_float(upper_bound):
        integrand = lambda y: gaussian(y, mean, standard_deviation)
        return integrate.quad(integrand, -np.inf, upper_bound)[0]
    return values.vectorize(greater)

相关问题 更多 >