将 S 曲线拟合到我的数据 - 无法调整参数以使曲线变陡

问题描述 投票:0回答:1

我正在使用以下代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def logistic(x, a, b, c, d=0):
    """
    Logistic function that maps x to a value between two asymptotes d and c.

    Parameters:
    - x: The independent variable or array of variables.
    - a: Defines the steepness of the curve.
    - b: Midpoint of the function where the maximum growth occurs.
    - c: The maximum value (upper asymptote) of the function.
    - d: The minimum value (lower asymptote) of the function, defaults to 0.

    Returns:
    - The calculated logistic value(s).
    """
    return d + (c - d) / (1 + np.exp(-a * (x - b)))

# Define the data
x = np.array([-4.49,-5.53,-6.66,-4.82,-7.01,-8.62,-9.86,-11.64,-12.41,-3.06,-4.48,-7.86,-3.09,
              -11.21,-2.01,-0.47,-4.60,-1.72,-4.21,-1.04,-2.90,-20.91,-2.47,-4.16,-2.81,-2.62,
              -2.57,-5.81,-7.34,-5.67,12.16,-6.82,-3.63,-20.75,-3.05,3.22,-0.91,-10.40,-3.66,
              -3.90,-4.69,60.39,-6.88,12.83,22.23,12.00,42.54,63.11,30.29,28.07,
              10.11,-2.99,2.18,1.14,1.49,-9.55])

y = np.array([0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.23,7.01,10.00,15.37,16.93,17.79,
              18.01,18.06,18.61,20.60,21.22,24.40,28.09,30.28,30.56,34.33,46.07,47.64,51.50,
              58.96,64.92,68.02,75.59,76.65,80.39,83.19,83.76,85.83,87.03,87.84,88.01,92.55,
              93.84,95.42,96.10,96.19,100.00,100.00,100.00,100.00,100.00,100.00,100.00,
              100.00,100.00,100.00,100.00,100.00])

# Use curve_fit to estimate the logistic function parameters
p0 = [1, 0, 1] # initial guesses for parameters a, b, and c
params, pcov = curve_fit(logistic, x, y, p0)

# Generate values for the x-axis to plot the curve
x_fit = np.linspace(x.min(), x.max(), 1000)

# Generate predictions for the y-axis using the estimated parameters
y_fit = logistic(x_fit, *params)

# Plot the data and the curve fit
plt.scatter(x, y)
plt.plot(x_fit, y_fit, 'r-', label='S-curve fit')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()

S 曲线无法正确拟合数据,我希望它更陡,并且限制为 0、1,反映更像我提供的图像中的内容

sample data with S-curve

但每次我调整参数时,曲线都会完全断裂,看起来像一条水平线

有人可以帮我吗?

python excel statistics
1个回答
0
投票

您的代码没有什么特别的问题 - 而是您的数据以某种方式被破坏了。

添加行

x = np.sort(x)

设置 x 之后、拟合之前。然后你就得到了

a, b, c =  1.0179736944407503 -3.9145795490586286 100.05506778222558

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.