如何为scipy.optimize.curve_fit的拟合函数传递参数?
curve_fit with a Fixed Dataset-Specific Parameter b Got it, let's break this down. You want to use scipy.optimize.curve_fit where a is the parameter we fit for, and b is a fixed value that changes depending on which dataset we're working with. Here are two straightforward, clean ways to make this work:
Method 1: Use a Closure (Nested Function)
A closure lets you define a "wrapper" function that takes your fixed b value, then returns the actual fitting function that uses this b. This keeps each dataset's b value isolated and avoids confusion.
import numpy as np from scipy.optimize import curve_fit def create_fit_func(b): # This inner function uses the `b` passed to the outer wrapper def fitfun(x, a): return np.exp(a * (x - b)) return fitfun # --- Example usage with two datasets --- # First dataset: b = 10 x_data1 = np.linspace(0, 20, 100) y_data1 = np.exp(0.1 * (x_data1 - 10)) + np.random.normal(0, 0.05, size=len(x_data1)) # Create a fit function bound to b=10 fit_func_b10 = create_fit_func(10) # Fit: curve_fit will only optimize `a` here popt1, pcov1 = curve_fit(fit_func_b10, x_data1, y_data1) print(f"Dataset 1 (b=10): Fitted a = {popt1[0]:.4f}") # Second dataset: b = 20 x_data2 = np.linspace(0, 30, 100) y_data2 = np.exp(0.08 * (x_data2 - 20)) + np.random.normal(0, 0.05, size=len(x_data2)) fit_func_b20 = create_fit_func(20) popt2, pcov2 = curve_fit(fit_func_b20, x_data2, y_data2) print(f"Dataset 2 (b=20): Fitted a = {popt2[0]:.4f}")
Method 2: Use functools.partial to Bind Fixed Parameters
If you prefer a more concise approach, functools.partial lets you "freeze" the b parameter in a base fitting function, leaving only a as the variable to optimize.
import numpy as np from scipy.optimize import curve_fit from functools import partial # Define a base function that includes both a and b as parameters def base_fitfun(x, a, b): return np.exp(a * (x - b)) # --- Example usage --- # For dataset 1, fix b=10 (use keyword argument to avoid ordering issues) fit_func_b10 = partial(base_fitfun, b=10) popt1, pcov1 = curve_fit(fit_func_b10, x_data1, y_data1) # For dataset 2, fix b=20 fit_func_b20 = partial(base_fitfun, b=20) popt2, pcov2 = curve_fit(fit_func_b20, x_data2, y_data2)
A Quick Note to Avoid Mistakes
Steer clear of using global variables for b—this can lead to bugs when switching between datasets, since the global value might get overwritten accidentally. Both methods above keep each dataset's b value contained and explicit.
内容的提问来源于stack exchange,提问作者Nisfa

