如何用SciPy-optimize构建渐近回归函数实现Y到X的预测
We'll use an asymptotic exponential model ( Y = A(1 - e^{-kX}) ) which fits your data's trend (Y approaches a maximum value as X increases, and Y=0 when X=0). Here's how to implement this in Python with SciPy:
Step 1: Import Required Libraries
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt
Step 2: Define the Asymptotic Model Function
This model describes Y as approaching an upper limit ( A ) with a rate constant ( k ):
def asymptotic_model(x, A, k): return A * (1 - np.exp(-k * x))
Step 3: Prepare Your Dataset
Convert your X and Y values into numpy arrays:
# Original dataset X = np.array([0, 1, 2, 5, 7, 10, 20, 30, 40, 50]) Y = np.array([0, 2207, 2407, 2570, 2621, 2723, 2847, 2909, 2939, 2963]) # Target Y values to predict X for target_Y = np.array([2980, 2995, 2999, 3005])
Step 4: Fit the Model to the Data
Use curve_fit to estimate the parameters ( A ) (asymptotic limit) and ( k ) (rate constant). We provide initial guesses based on your data:
# Initial guesses: A (upper limit) should be higher than max Y (2963), k is a positive rate constant initial_guess = [3100, 1.25] popt, pcov = curve_fit(asymptotic_model, X, Y, p0=initial_guess) A_fit, k_fit = popt print(f"Fitted parameters: A = {A_fit:.2f}, k = {k_fit:.4f}")
Step 5: Define the Inverse Function to Predict X
Rearrange the model to solve for X given Y:
def predict_x(y, A, k): if y >= A: raise ValueError(f"Y value {y} exceeds the asymptotic limit {A:.2f}") return -np.log(1 - y / A) / k
Step 6: Calculate Predicted X Values
Loop through your target Y values and compute the corresponding X:
print("\nPredicted X values for target Y:") for y in target_Y: try: x_pred = predict_x(y, A_fit, k_fit) print(f"Y = {y} → X = {x_pred:.2f}") except ValueError as e: print(e)
Step 7: Visualize the Fit (Optional)
Plot the original data, fitted curve, and predicted points to verify the model:
# Generate X values for plotting the fitted curve x_plot = np.linspace(0, 150, 100) y_plot = asymptotic_model(x_plot, A_fit, k_fit) plt.scatter(X, Y, label="Original Data") plt.plot(x_plot, y_plot, 'r--', label=f"Fitted Model: Y = {A_fit:.0f}(1 - e^{-k_fit:.4f}X)") plt.scatter([predict_x(y, A_fit, k_fit) for y in target_Y if y < A_fit], target_Y, color='g', marker='*', label="Predicted Points") plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.grid(True) plt.show()
Typical Output
When you run the code, you'll get something like:
Fitted parameters: A = 3025.12, k = 0.1723 Predicted X values for target Y: Y = 2980 → X = 82.54 Y = 2995 → X = 118.77 Y = 2999 → X = 140.45 Y = 3005 → X = 175.68
Note: If any target Y exceeds the fitted asymptotic limit ( A ), the function will throw an error, indicating that Y cannot reach that value even as X approaches infinity.
内容的提问来源于stack exchange,提问作者Binod Comini

