[Python] Instability in fitting data using Scipy Optimize library

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to fit a function to a set of data I have. The function in question is:

    x(t) = - B + sqrt(AB(t-t0) + (x0 + B)^2)

    I have tried to fit my data (included at the bottom) to this using two different methods but have found that whatever I do the fit for B is extremely unstable. Changing either the method or the initial guess wildly changes the output value. In addition, when I look at the error for this fit using curve_fit the error is almost two orders of magnitude higher than the value. Does anyone have some suggestions on what I should do to decrease the error?

    import numpy as np
    import scipy.optimize as spo

    def modelFun(t,A,B):
    return -B + np.sqrt(A*B*(t-t0) + np.power(x0 + B,2))

    def errorFun(k,time,data):
    A = k[0]
    B = k[1]
    return np.sum((data-modelFun(time,A,B))**2)

    data = np.genfromtxt('testdata.csv',delimiter=',',skip_header = 1)
    time = data[:,0]
    xt = data[:,1]
    t0 = data[0,0]
    x0 = data[0,1]

    minErrOut = spo.minimize(errorFun,[1,1000],args=(time,xt),bounds=((0,None),(0,None)))
    (curveOut, curveCovar) = spo.curve_fit(modelFun,time,xt,p0=[1,1000],method='dogbox',bounds=([-np.inf,0],np.inf))

    print('minimize result: A={}; B={}'.format(*minErrOut.x))
    print('curveFit result: A={}; B={}'.format(*curveOut))
    print('curveFit Error: A={}; B={}'.format(*np.sqrt(np.diag(curveCovar))))


    Datafile:

    Time,x
    201,2.67662
    204,3.28159
    206,3.44378
    208,3.72537
    210,3.94826
    212,4.36716
    214,4.65373
    216,5.26766
    219,5.59502
    221,6
    223,6.22189
    225,6.49652
    227,6.799
    229,7.30846
    231,7.54229
    232,7.76517
    233,7.6209
    234,7.89552
    235,7.94826
    236,8.17015
    237,8.66965
    238,8.66965
    239,8.8398
    240,8.88856
    241,9.00697
    242,9.45075
    243,9.51642
    244,9.63483
    245,9.63483
    246,10.07861
    247,10.02687
    248,10.24876
    249,10.31443
    250,10.47164
    251,10.99502
    252,10.92935
    253,11.0995
    254,11.28358
    255,11.58209
    256,11.53035
    257,11.62388
    258,11.93632
    259,11.98806
    260,12.26269
    261,12.43284
    262,12.60299
    263,12.801
    264,12.99502
    265,13.08557
    266,13.25572
    267,13.32139
    268,13.57114
    269,13.76617
    270,13.88358
    271,13.83184
    272,14.10647
    273,14.27662
    274,14.40796

    Continue reading...

Compartilhe esta Página