尝试拟合数据函数的曲线

问题描述 投票:0回答:1

为了使用拟合函数准确地将曲线拟合到我的数据,我需要遵循结构化方法。目前的拟合曲线不正确,我该如何进行才能达到正确的拟合?
这是我的代码:

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

#  Fit function 
def fit_function(epsilon, T, Delta_E, hbar_omega):                           
    term1 = np.exp(-(epsilon - Delta_E) / T)
    term2 = np.exp((4 * np.pi * Delta_E / hbar_omega) * (np.sqrt(epsilon / Delta_E) - 1))
    term3 = term2 + 1
    return term1 * term2 / term3

# Define the function that generates your example data
def data(x, a, b, c, d):
    return a * (1 - np.exp(-b * x)) * np.exp(-c * x) + d

# Example data (replace these arrays with your actual data)
epsilon_data = np.linspace(0.01, 10, 100)  # Kinetic energy values
distribution_data = data(epsilon_data, 2.5e6, 10, 1, 0)  # Example distribution

# Initial guess for T, Delta_E, hbar_omega
p0 = [1, 1, 1]

# Fit the fit_function to the distribution_data
popt, pcov = curve_fit(fit_function, epsilon_data, distribution_data, p0=p0, maxfev=8000)

# Plot the comparison of data and fitted curve
plt.scatter(epsilon_data, distribution_data, label='Data', color='blue')
plt.plot(epsilon_data, fit_function(epsilon_data, *popt), label='Fitted Curve', color='red')
plt.xlabel('Kinetic Energy (ε)')
plt.ylabel('Distribution')
plt.legend()
plt.show()
python curve-fitting
1个回答
0
投票

提供有根据的猜测和界限有助于提高健康水平:

p0 = [1, 10, 10]

popt, pcov = curve_fit(
    fit_function, epsilon_data, distribution_data, p0=p0,
    bounds=[
        (0., 0., 0.),
        (np.inf, np.inf, np.inf)
    ]
)

enter image description here

但显然不令人满意。这个问题可能与

curve_fit
本身无关,更多的是关于您正在将已知模型
data
与完全不同的模型
fit_function
进行拟合这一事实:

enter image description here

模型差异太大,无法一致。

确实你原来的函数可以回归:

popt2, pcov2 = curve_fit(data, epsilon_data, distribution_data)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.