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

如何用Python Logistic Regression实现带非线性未来预测的数据绘图?

实现非线性预测绘图+Logistic Regression预测方案

1. 为什么你之前只得到直线?

  • 大概率是直接使用了线性回归,或是对Logistic Regression的用法有误——Logistic Regression默认是分类任务,直接拟合原始连续数据时,若不做特征处理,会得到近似线性的结果。
  • 另外,未对输入特征做非线性变换(如多项式特征、归一化),也会导致非线性模型拟合出直线效果。

2. 示例图非线性预测的核心逻辑

示例图的非线性预测本质是用非线性模型拟合历史数据,再外推未来值,核心步骤:

  • 匹配数据趋势选择对应非线性模型(比如Logistic回归适合饱和增长、多项式回归适合波动趋势)
  • 对历史数据做特征工程(如时间特征变换、归一化)
  • 拟合模型后生成未来时间点的特征,代入模型得到预测值,最后整合历史数据、拟合曲线、预测结果绘图

3. 用Python结合Logistic Regression实现非线性预测(饱和增长场景)

Logistic回归的S型曲线天然适配有增长上限的非线性场景(比如用户增长、产品销量饱和),以下是完整可运行的实现代码:

步骤1:导入依赖库

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

步骤2:准备模拟/真实历史数据

这里模拟示例图的饱和增长趋势,你可以替换为自己的真实数据:

# 历史时间维度(比如第1到20天)
X_history = np.arange(1, 21).reshape(-1, 1)
# 历史观测值(模拟带噪声的S型增长)
y_history = 100 / (1 + np.exp(-0.3*(X_history - 10))) + np.random.normal(0, 3, size=X_history.shape)

步骤3:数据预处理+拟合Logistic模型

注意:将Logistic回归作为广义线性模型拟合连续值时,需要对特征和目标值做尺度处理:

# 归一化特征(Logistic回归对特征尺度敏感)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_history)

# 初始化模型:调大C值降低正则化强度,保证拟合非线性趋势
model = LogisticRegression(solver='lbfgs', C=1000, max_iter=1000)
# 将目标值归一化到[0,1]区间,适配Logistic的概率输出逻辑
y_scaled = (y_history - y_history.min()) / (y_history.max() - y_history.min())
model.fit(X_scaled, y_scaled.ravel())

步骤4:生成未来预测数据

# 生成未来时间点(比如第21到30天)
X_future = np.arange(21, 31).reshape(-1, 1)
# 对未来特征做归一化
X_future_scaled = scaler.transform(X_future)
# 预测并转换回原始数值尺度
y_fhat_scaled = model.predict_proba(X_future_scaled)[:, 1]
y_future = y_fhat_scaled * (y_history.max() - y_history.min()) + y_history.min()

步骤5:绘制历史数据+拟合+预测曲线

plt.figure(figsize=(10,6))
# 绘制历史数据点
plt.scatter(X_history, y_history, color='blue', label='历史数据')
# 绘制历史拟合曲线
y_history_fhat_scaled = model.predict_proba(X_scaled)[:,1]
y_history_fhat = y_history_fhat_scaled * (y_history.max() - y_history.min()) + y_history.min()
plt.plot(X_history, y_history_fhat, color='green', label='拟合曲线')
# 绘制未来预测曲线
plt.plot(X_future, y_future, color='red', linestyle='--', label='未来预测')

plt.xlabel('时间')
plt.ylabel('数值')
plt.title('历史数据拟合与未来预测')
plt.legend()
plt.grid(True)
plt.show()

4. 额外优化建议

  • 若你的数据是其他非线性趋势(如指数增长、多项式波动),可以结合sklearn.preprocessing.PolynomialFeatures做特征变换,再用线性回归或其他模型拟合
  • 要实现示例图的交互式效果,可替换matplotlib为plotly,支持缩放、悬浮显示数值等功能
  • 拟合后需验证模型效果,比如计算均方误差(MSE),调整模型参数(如Logistic的C值、迭代次数)提升拟合精度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:55:16