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

Python中Curve_fit拟合Sigmoid曲线问题咨询:曲线未叠加散点图及ValueError报错

Fixing Your Sigmoid Plot & ValueError Issues

Let's break down and solve your two problems step by step:

1. Why You're Getting ValueError: object too deep for desired array

This error almost always happens because scipy.optimize.curve_fit expects 1-dimensional arrays for input data, but your xdata or ydata is likely 2-dimensional (e.g., shaped like (n, 1) instead of (n,)).

To fix this, flatten your arrays to 1D using methods like flatten() or ravel() when preparing data for curve_fit.

2. Why the Sigmoid Curve Isn't Showing Over Your Scatter Data

There are a few key issues here:

  • Mismatched variable names: You used plt.plot(X, y, 'ro') for scatter points, but your data variables are x_data and y_data — make sure these are consistent.
  • Missing the fitted curve: Your code only plots the initial sigmoid guess, not the optimized curve generated by curve_fit.
  • Scaling mismatch: The initial sigmoid is scaled by an arbitrary large number (15000000000000.) which might not align with your actual data range. Using your raw data's max value to reverse normalization is far more reliable.

Corrected Full Code

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

# Define the sigmoid function
def sigmoid(x, Beta_1, Beta_2):
    y1 = 1 / (1 + np.exp(-Beta_1*(x-Beta_2)))
    return y1

# Replace this with your actual x_data and y_data
# Example dummy data if you need it:
# x_data = np.linspace(1950, 2020, 70)
# y_data = 1.5e13 / (1 + np.exp(-0.1*(x_data-1990))) + np.random.normal(0, 0.5e12, len(x_data))

# Initial guess parameters
beta_1 = 0.10
beta_2 = 1990.0

# Generate initial sigmoid prediction
Y_pred = sigmoid(x_data, beta_1, beta_2)

# Plot initial guess vs raw data
plt.figure(figsize=(10,6))
# Use consistent variable names for scatter points
plt.plot(x_data, Y_pred * np.max(y_data), label='Initial Sigmoid Guess')
plt.scatter(x_data, y_data, color='red', label='Raw Data Points')

# Normalize data and flatten to 1D for curve fitting
xdata = x_data.flatten() / np.max(x_data)
ydata = y_data.flatten() / np.max(y_data)

# Perform curve fitting with properly shaped arrays
popt, pcov = curve_fit(sigmoid, xdata, ydata)
print(f"Optimized beta_1 = {popt[0]:.6f}, beta_2 = {popt[1]:.6f}")

# Generate and plot the fitted sigmoid curve (reverse normalization)
x_fit = np.linspace(np.min(x_data), np.max(x_data), 100)
x_fit_normalized = x_fit / np.max(x_data)
y_fit_normalized = sigmoid(x_fit_normalized, *popt)
y_fit = y_fit_normalized * np.max(y_data)

plt.plot(x_fit, y_fit, color='green', linewidth=2, label='Fitted Sigmoid Curve')

plt.xlabel('X Data')
plt.ylabel('Y Data')
plt.legend()
plt.show()

Key Fixes Explained:

  • Added .flatten() to x_data and y_data to ensure they're 1D, resolving the ValueError.
  • Used np.max(y_data) to scale sigmoid predictions, ensuring alignment with your raw data's range.
  • Added code to generate and plot the optimized fitted curve, so it appears over your scatter points.
  • Standardized variable names to avoid mismatches between data and plotting calls.

内容的提问来源于stack exchange,提问作者user18071561

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:37:29