You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 t first, followed by parameters k1 and k2—this matches curve_fit's required input format.
  • Numpy Operations: Used np.exp instead of raw exp to handle array-based calculations correctly.
  • Parameter Handling: k1 and k2 are now function arguments, so curve_fit can optimize their values. Fixed the multiplication syntax (k1 * (...) instead of k1(...)).
  • Initial Guess: Added p0=initial_guess to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:13:20