在Python中实现指数增长函数的曲线拟合
Got it, let's walk through how to perform exponential growth curve fitting on your dataset using Python. I'll break this down into actionable steps with code examples you can adapt directly.
First, we need a function that represents exponential growth. The standard form (for data that grows from an initial value) is:
def exponential_growth(t, a, b): # a = initial value of the curve, b = growth rate constant return a * np.exp(b * t)
If your data has a baseline offset (i.e., it doesn't start near zero), use this modified version instead:
def exponential_growth_with_offset(t, a, b, c): # c = baseline value that the curve grows from return c + a * np.exp(b * t)
We'll start with the standard model, but you can switch to the offset version if your data needs it.
Looking at your t values (all around 15,000), directly plugging them into np.exp(b*t) can cause numerical overflow—even small b values will make the exponent huge. Fix this by centering your time data (subtract the mean of t):
t_centered = t - np.mean(t)
This keeps the exponent values manageable without changing the shape of the growth curve.
Use scipy.optimize.curve_fit to find the best-fit parameters. Adding an initial guess (p0) helps the optimizer converge better—adjust this based on your data's trend.
Here's the full, runnable code snippet (including your imports and truncated data):
import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit # Your time data (truncated example; replace with your full dataset) t = np.array([15474.6, 15475.6, 15476.6, 15477.6, 15478.6, 15479.6, 15480.6, 15481.6, 15482.6, 15483.6, 15484.6, 15485.6]) # Replace this with your actual measurement values y = np.array([...]) # Insert your corresponding y-data here # Define the growth function def exponential_growth(t, a, b): return a * np.exp(b * t) # Center time data to avoid numerical overflow t_centered = t - np.mean(t) # Perform curve fit with initial guess (tweak p0 based on your data) popt, pcov = curve_fit(exponential_growth, t_centered, y, p0=[1, 0.001]) # Extract fitted parameters a_fit, b_fit = popt # Generate fitted y-values y_fit = exponential_growth(t_centered, a_fit, b_fit) # Plot results to visualize the fit plt.scatter(t, y, label='Original Data') plt.plot(t, y_fit, 'r-', label=f'Fitted Curve: y = {a_fit:.2f} * exp({b_fit:.4f}*(t - {np.mean(t):.1f}))') plt.xlabel('Time (t)') plt.ylabel('Measured Value') plt.legend() plt.show() # Convert the fit back to use original (uncentered) t if needed a_original = a_fit * np.exp(-b_fit * np.mean(t)) print(f"Fit in original time scale: y = {a_original:.2f} * exp({b_fit:.4f}*t)")
- Initial Guess (
p0): If the fit fails to converge, adjustp0to values that make sense for your data. For example, if your starting y-value is ~50 and growth is slow, tryp0=[50, 0.0001]. - Overflow Warnings: If you still get overflow errors, try scaling the time data (e.g., divide by 1000) instead of centering.
- Evaluate Fit Quality: Calculate the R-squared value to check how well the model matches your data:
residuals = y - y_fit ss_res = np.sum(residuals**2) ss_total = np.sum((y - np.mean(y))**2) r_squared = 1 - (ss_res / ss_total) print(f"R-squared (fit quality): {r_squared:.4f}")
内容的提问来源于stack exchange,提问作者wigging

