Python找到稍微包含垂直面的曲线拟合

2024-10-02 02:37:37 发布

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

我有一组数据点在双轴刻度上。我想符合这些要点。数据点的数量达到几千个。这里,我给出了可复制的形状数据点

我的代码:

from scipy.optimize import curve_fit

x1 = [327.98999023, 327.98999023, 328.02999878, 367.6499939 ,
       374.72000122, 372.73001099, 372.95001221, 373.02999878,
       379.39001465, 375.58999634, 378.97000122, 378.1499939 ,
       380.70001221, 379.42999268, 379.5       , 379.5       ,
       392.22000122, 379.57998657, 376.67999268, 376.67999268]
ym1 = [2.54999995, 2.73999989, 2.91000009, 2.96999991, 3.17000002,
       3.40000004, 3.60000014, 3.77999991, 3.98999989, 4.21000004,
       4.44000006, 4.62000012, 4.83999997, 5.19999981, 5.32999992,
       5.59000015, 5.88999987, 6.20000005, 6.46000028, 6.66999996] 

def testfit(x, *p):
    ''' function to fit the indentation curve 
    p = [x0,c, poly1d_coeffs ]'''
    x = x.astype(float)
    y = p[1]*(1-sigmoid(x-p[0],k=1)) + np.poly1d(p[2:])(x) * sigmoid(x-p[0],k=1)
    return y

def sigmoid(x, k=1):
    return 1/(1+np.exp(-k*x))

p0_guess = (30, 5, 0.3, -10 )
popt, pcov = curve_fit(testfit, x1, ym1, p0=p0_guess)    # find optimal parameters
# calculate prediction
yp1 = testfit(x1,popt[0],popt[1],popt[2])
# calculate r^2
r1 = r2_score(ym1,yp1)
print(r1)
plt.plot(x1,ym1,'.')
plt.plot(x1,yp1,'-')
plt.show()

目前产出:

r1
Out[128]: -2.1490993028157854 # Negative fit score, Really bad fit. 

enter image description here


Tags: 数据defnppltfitx1curver1

热门问题