Skip to main content
 首页 » 编程设计

python之curve_fit 没有优化其中一个参数

2024年09月07日1252php

我需要适应scipy.optimize.curve_fit一些看起来像图中点的数据。我使用函数 y(x) (见下面的 def)它给出了一个常量 y(x)=c对于 x<x0 ,否则为多项式(例如第二条倾斜线 y1 = mx+q )。

我对参数 (x0, c, m, q) 给出了一个合理的初始猜测,如图所示。拟合结果表明,除第一个参数外,所有参数均已优化 x0 .

为什么会这样? 这是我定义函数的方式吗 testfit(x, *p) , 其中x0 (= p[0] ) 出现在另一个函数中?

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit 
 
# generate some data: 
x = np.linspace(0,100,1000) 
y1 = np.repeat(0, 500) 
y2 = x[500:] - 50 
y = np.concatenate((y1,y2)) 
y = y + np.random.randn(len(y)) 
 
 
def testfit(x, *p): 
    ''' piecewise function used to fit  
        it's a constant (=p[1]) for x < p[0] 
        or a polynomial for x > p[0]      
    ''' 
    x = x.astype(float) 
    y = np.piecewise(x, [x < p[0], x >= p[0]], [p[1], lambda x: np.poly1d(p[2:])(x)]) 
    return y 
 
# initial guess, one horizontal and one tilted line: 
p0_guess = (30, 5, 0.3, -10) 
 
popt, pcov = curve_fit(testfit, x, y, p0=p0_guess) 
 
print('params guessed  : '+str(p0_guess)) 
print('params from fit : '+str(popt)) 
 
plt.plot(x,y, '.') 
plt.plot(x, testfit(x, *p0_guess), label='initial guess') 
plt.plot(x, testfit(x, *popt), label='final fit') 
plt.legend() 

输出

params guessed  : (30, 5, 0.3, -10)  
params from fit : [ 30. 0.04970411   0.80106256 -34.17194401]  
 
OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) 

请您参考如下方法:

按照 kazemakase 的建议,我通过我用来拟合的两个函数之间的平滑过渡解决了这个问题(一条水平线后跟一个多项式)。诀窍是将一个函数乘以 sigmoid(x),将另一个函数乘以 1-sigmoid(x),(其中 sigmoid(x)定义如下)。

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit 
 
x = np.linspace(0,100,1000) 
y1 = np.repeat(0, 500) 
y2 = x[500:] - 50 
y = np.concatenate((y1,y2)) 
y = y + np.random.randn(len(y)) 
 
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, x, y, p0=p0_guess) 
print('params guessed  : '+str(p0_guess)) 
print('params from fit : '+str(popt)) 
 
 
plt.figure(1) 
plt.clf() 
plt.plot(x,y, 'y.') 
plt.plot(x, testfit(x, *p0_guess), label='initial guess') 
plt.plot(x, testfit(x, *popt), 'k', label='final fit') 
plt.legend()