[Python] Fitting sigmoid functions

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have some data I am trying to fit to a sigmoid function (several parameters for several species), however apparently some of them don't look fitted in a good way, I don't understand where the mistake is. I also got some warning:


    RuntimeWarning: overflow encountered in exp
    y = a / (1 + np.exp(-c * (x - d))) + b
    OptimizeWarning: Covariance of the parameters could not be estimated
    warnings.warn('Covariance of the parameters could not be estimated'
    ​

    But I don't really know how to improve this

    def sigmoid(x, a, b, c, d):
    y = a / (1 + np.exp(-c * (x - d))) + b
    return (y)

    fig, axes = plt.subplots(
    nrows=len(params),
    ncols=len(species_list),
    figsize=(15, 18),
    sharex='col',
    sharey='row'
    )

    legend_handles = []
    legend_labels = []

    for i, param in enumerate(params):
    for j, species in enumerate(species_list):
    ax = axes[i, j]
    species_subset = df[df['Species'] == species]

    for treatment in species_subset['Treatment'].unique():
    treatment_subset = species_subset[species_subset['Treatment'] == treatment]

    x = treatment_subset['RWC'].values
    y = treatment_subset[param].values
    mask = np.isfinite(x) & np.isfinite(y)
    x_clean = x[mask]
    y_clean = y[mask]

    scatter = ax.scatter(x_clean, y_clean, label=treatment, alpha=0.6)

    if len(x_clean) > 2:
    try:
    p0 = [max(y_clean), np.median(x_clean),1,min(y_clean)]
    popt, _ = curve_fit(sigmoid, x_clean, y_clean, p0, maxfev=10000)
    x_fit = np.linspace(x_clean.min(), x_clean.max(), 100)
    y_fit = sigmoid(x_fit, *popt)
    ax.plot(x_fit, y_fit, linestyle='--')
    except RuntimeError:
    print(f"Fit failed for {species}, {param}, {treatment}")
    else:
    print(f"Not enough data for {species}, {param}, {treatment} — skipping fit")

    if i == 0 and j == 0:
    legend_handles.append(scatter)
    legend_labels.append(treatment)

    if i == 0:
    ax.set_title(species)
    if j == 0:
    ax.set_ylabel(param)
    ax.set_xlabel('RWC')
    ax.tick_params(axis='x', rotation=45)
    ax.grid(True)

    fig.legend(
    legend_handles,
    legend_labels,
    title='Treatment',
    loc='upper right',
    bbox_to_anchor=(0.99, 0.99)
    )

    plt.tight_layout(rect=[0, 0, 0.95, 1])
    plt.show()


    This is the output I get: [​IMG]

    Continue reading...

Compartilhe esta Página