最小化置信区间usign scipy最小化

时间:2018-02-27 10:07:38

标签: python scipy

我的目标是找到最短的间隔,其中我的概率密度函数下的面积等于0.2。我的PDF在区间[x_min,x_max]上是明确的。

这意味着,我想最小化功能

lambda x: x[1] - x[2]

满足这个条件:

1] x_max - x [1]> = 0

2] x [0] - x_min> = 0

3]从x [0]到x [1] - 0.2 = 0

的整合(PDF)

这是我的代码:

from math import exp, log
from scipy.stats import logistic, norm
import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize

###################functions#################

#pdf function for logit
def pdf1(x_i, intercept, coef, x0):
    a = (exp(intercept)*coef*((x_i + x0)**(coef - 1)))/(((exp(intercept)*
        ((x_i+x0)**coef)) + 1)**2)
    return a

#pdf function for logistic distribution
def pdf2(x_i, mi, s):
    return logistic.pdf(x_i, mi, s)

#pdf function for normal distribution
def pdf3(x_i, loc, scale):
    return norm.pdf(x_i, loc = loc, scale = scale)

def pdf_point(x, p, const, params_logit, params_logistic, params_gauss):
    p1, p2 = p
    intercept, coef, x0 = params_logit
    mi, s = params_logistic
    loc, scale = params_gauss
    a = const*(p1 * pdf1(x, intercept, coef, x0) + p2* pdf2(x, mi, s) + (1 - p1 - p2)*pdf3(x, loc, scale))
    return a


def integrate_pdf(x, p, const, params_logit, params_logistic, params_gauss):
    x1, x2 = x
    return quad(pdf_point, x1, x2, args = (p, const, params_logit, params_logistic, params_gauss)) - 0.2


#############parameters#############
p = [ 0.22215561,  0.77784439]
const = 1.1514406903526164
params_logit = [-654.14149905436966, 109.50138530596364, 362.80446670967461]
params_logistic = (32.96514363428475, 2.8362675341927019)
params_gauss = (32.12488888888889, 5.4151936960216025)
mi = 18.0
ma = 38.399999999999999


##############code for my goal##############

con = ({"type" : "eq","fun" : integrate_pdf, "args" : (p, const, params_logit, params_logistic, params_gauss)},
       {"type" : "ineq", "fun" : lambda x : x[0] - mi},{"type" : "ineq", "fun" : lambda x: ma - x[1]})

b = minimize(lambda x: x[1] - x[0], [1,1], method = "SLSQP", constraints = con)

不幸的是,它返回了我的错误,我不明白最新情况

这是错误:

    return quad(pdf_point, x1, x2, args = (p, const, params_logit, params_logistic, params_gauss)) - 0.2

TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

0 个答案:

没有答案
相关问题