Python实现:将导入数据拟合至指定方程并提取k1、k2参数
Solution
Corrected Code
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Use the provided dataset directly (replace with csv loading if needed) Time = np.array([1, 1.25, 2.5, 3.75, 5, 6.25, 7.5, 8.75, 10]) AB = np.array([0.041355887, 0.228856274, 0.283712222, 0.401528071, 0.450842768, 0.514348728, 0.550876642, 0.61845291, 0.663312161]) # Define the fitting equation correctly def binding_model(t, k1, k2): return k1 * (1 - np.exp(-k2 * t)) # Initial guess for parameters (k1 = asymptotic value, k2 = rate constant) initial_guess = [0.7, 0.5] # Run curve fitting popt, pcov = curve_fit(binding_model, Time, AB, p0=initial_guess) # Extract optimized parameters k1_opt, k2_opt = popt print(f"Optimized k1: {k1_opt:.4f}") print(f"Optimized k2: {k2_opt:.4f}") # Generate smooth fitted curve data t_fit = np.linspace(min(Time), max(Time), 100) ab_fit = binding_model(t_fit, k1_opt, k2_opt) # Plot original data and fitted curve plt.figure(figsize=(8, 6)) plt.scatter(Time, AB, label='Original Data', color='blue') plt.plot(t_fit, ab_fit, label=f'Fitted Curve: AB(t) = {k1_opt:.4f}(1 - e^(-{k2_opt:.4f}t))', color='red') plt.xlabel('Time') plt.ylabel('AB') plt.title('Binding Data Fitting') plt.legend() plt.grid(True) plt.show()
Key Fixes & Explanations
- Function Structure: The fitting function now takes the independent variable
tfirst, followed by parametersk1andk2—this matchescurve_fit's required input format. - Numpy Operations: Used
np.expinstead of rawexpto handle array-based calculations correctly. - Parameter Handling:
k1andk2are now function arguments, socurve_fitcan optimize their values. Fixed the multiplication syntax (k1 * (...)instead ofk1(...)). - Initial Guess: Added
p0=initial_guessto help the fitting algorithm converge faster (based on the asymptotic value of AB and a reasonable rate constant). - Plotting: Added code to generate a smooth fitted curve and visualize it alongside raw data, with clear labels and a legend.
Optional: Load Data from CSV
If you prefer to use your binding.csv file instead of the provided lists, replace the data definition section with:
import pandas as pd df = pd.read_csv('binding.csv') Time = df['Time'].values AB = df['AB'].values
Ensure your CSV has columns named Time and AB.
内容的提问来源于stack exchange,提问作者HAILEY RUDE
相关产品推荐
相关产品推荐

