简体   繁体   中英

SciPy curve_fit doesn't try to shift Lorentzian's peak

I have some Lorentzian data that I'm trying to fit and am having problems with. I figured maybe it's too noisy for scipy to find a good fit, so I generated an idealised Lorentzian to fit to instead, and to my surprise, scipy can't fit to that, either, with a nearly perfect initial guess. In this case, all scipy needs to do is shift the peak of the Lorentzian over less than 1%, though it fails with arbitrarily accurate initial guesses.

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

def lorentzian(freq, gamma, center_freq, amplitude):
    return amplitude * gamma**2 / ( gamma**2 + ( freq - center_freq )**2) + 1

frequencies = np.arange(4.95e9, 5.05e9, 0.1e9/1000)

guess = [15000000, 4.997e9, 28]
fake = [15000000, 5.02e9, 28]
test_data = lorentzian(frequencies, *fake)
popt, pcov = curve_fit(lorentzian, test_data, frequencies, maxfev = 100000, p0 = guess)
fit_lorentzian = lorentzian(frequencies, *popt)
guess_lorentzian = lorentzian(frequencies, *guess)
plt.plot(frequencies, test_data)
plt.plot(frequencies, fit_lorentzian)

测试数据与拟合

scipy warns me OptimizeWarning: Covariance of the parameters could not be estimated warnings.warn('Covariance of the parameters could not be estimated', and returns the initial guess as popt. pcov is a 3x3 array of inf. What's going on?

As pointed out in the comments, curve_fit has arguments (f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(- inf, inf), method=None, jac=None, **kwargs) ; ie, I swapped the order of the x data and y data. popt, pcov = curve_fit(lorentzian, frequencies, test_data, maxfev = 100000, p0 = guess) solves it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM