使用scipy.integrate.quad的Python最小二乘法

时间:2013-09-21 00:47:20

标签: python numpy scipy least-squares

我无法为我的代码解密错误消息,以便找到适合两个参数(eps和sig)的复杂最小二乘法的参数。

from pylab import *
import scipy
import numpy as np

from scipy import integrate, optimize

# Estimate parameters with least squares fit   
T = [90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300]
B = [-0.2221, -0.18276, -0.15348, -0.13088, -0.11293, -0.09836, -0.086301, -0.076166, -0.067535, -0.060101, -0.053636, -0.047963, -0.04295, -0.038488, -0.034494, -0.030899, -0.027648, -0.02469, -0.022, -0.019534, -0.017268, -0.015181]


def funeval(Temp,eps,sig):
    return -2.*np.pi*scipy.integrate.quad( lambda x: np.exp(4.*eps/Temp*((sig/x)**6.-(sig/x)**12.)*(x**2)) ,0.0,Inf )[0]

def residuals(p,y,Temp):
    eps,sig = p
    err = y-(funeval(Temp,eps,sig) )
    return err

print funeval(90.,0.001, 0.0002) 

plsq = scipy.optimize.leastsq(residuals, [0.00001, 0.0002], args=(B, T))

funeval给出了合理的浮点数,但是当我运行代码时它会返回:

error: Supplied function does not return a valid float.

错误似乎对初始条件不敏感。我是python的新手,所以任何帮助或指导帮助都会非常感激。感谢。

1 个答案:

答案 0 :(得分:2)

使用funeval(90.,0.001, 0.0002)Temp是一个奇异值;但是,当您致电scipy.optimize时,您将整个T数组传递给funeval,导致scipy.integrate崩溃。

快速解决方法是执行以下操作:

def funeval(Temp,eps,sig):
    out=[]
    for T in Temp:
        val = scipy.integrate.quad( lambda x: np.expm1( ((4.*eps)/T)* ((sig/x)**12.-(sig/x)**6.)* (x**2.) ), 0.0, np.inf )[0]
        out.append(val)
    return np.array(out)

def residuals(p,y,Temp):
    eps,sig = p
    err = y-(funeval(Temp,eps,sig) )
    return err

print funeval([90],0.001, 0.0002)

plsq = scipy.optimize.leastsq(residuals, [0.00001, 0.0002], args=(B, T))
(array([  3.52991175e-06,   9.04143361e-02]), 1)

遗憾的是,这并没有很好地融合。你能解释一下你想要做什么吗?