scipy.optimize失败,初始猜测很好

时间:2019-11-04 14:17:31

标签: python python-3.x scipy

我正在尝试将a*tanh(b*x) + c形式的函数适合我的数据,如下所示:

x = [1. , 2.,  3.,  5.,  6., 10., 15., 30.]
y = [1., 1.81498639,  2.51864814,  3.54771826,  3.99775936,  5.74444049,
     8.06357414, 12.82164541]

我使用的是scipy.optimize.curve_fit,但得到的结果不正确,导致出现以下情况: Failed regression 起初,我认为也许我的最初猜测很不好/需要提供,所以我手动估算了一个很好的拟合值,然后将这些值作为p0 arg到curve_fit()的形式提供。这只会导致更差的逼近,曲线在数据上方的y轴上升高了约1000个单位。

拟合度如何过高?我是否需要为curve_fit函数指定更多的参数才能获得有意义的结果?

错误消息:

OptimizeWarning:无法估计参数的协方差   category = OptimizeWarning

我的代码:

import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt


def fit(a,b,c,X):

    eq = a*np.tanh(b*X) + c
    return eq

def check_plot(x,y,lam,tp,mol,X,Y):

    '''
    Creates a plot of s_ineff vs t_block to check
    for correct selection of block sizes, which
    still produce consistent results.
    '''

    fig, ax = plt.subplots(figsize=(7,4))

    ax.scatter(x,y)
    ax.plot(X,Y,c='r')
    ax.set_ylabel(r'$s_{ineff}$')
    ax.set_xlabel(r'$\tau_{Block}$')
    ax.text(0.04, 0.95,
            '%s\n$\lambda_{%s} = %s$'%(mol,tp,lam),
            horizontalalignment='left',
            verticalalignment='top',
            transform=ax.transAxes)

#    plt.savefig("fitti.png",bbox_inches="tight",dpi=300)
    plt.show()
    plt.close(fig)

x = np.array([1. , 2.,  3.,  5.,  6., 10., 15., 30.])
y = np.array([1., 1.81498639,  2.51864814,  3.54771826,  3.99775936,  5.74444049,
     8.06357414, 12.82164541])


parms, parms_cov = optimize.curve_fit(fit, x, y)

a,b,c = parms[0],parms[1],parms[2]
# good initial guess: p0=[13,0.05,0.6]       
X,Y = x,fit(a,b,c,x)

mol,tp,lam = 'toluene','elec',0.15

check_plot(x,y,lam,tp,mol,X,Y)

0 个答案:

没有答案