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

时间序列稳定点筛选、绘制及线性回归实现求助

时间序列稳定点筛选、可视化与线性回归实现

1. 筛选稳定点

核心逻辑是保留连续相邻点差值绝对值<0.005的点集,避免误选过渡阶段的孤立小差值点。以下是两种实现方式:

方式1:循环遍历(直观易调试)

import pandas as pd
import numpy as np

# 读取你的时间序列数据(假设结构为time列、value列)
df = pd.read_csv("your_data.csv")

# 计算相邻value的差值绝对值
df["abs_diff"] = df["value"].diff().abs()

# 标记稳定点:仅保留连续满足差值条件的点
df["is_stable"] = False
df.loc[0, "is_stable"] = True  # 初始化第一个点

for idx in range(1, len(df)):
    # 当前点与前一个点差值达标,且前一个点是稳定点时,标记为稳定
    if df["abs_diff"].iloc[idx] < 0.005 and df["is_stable"].iloc[idx-1]:
        df.loc[idx, "is_stable"] = True

# 提取稳定点数据集
stable_points = df[df["is_stable"]].drop(["abs_diff", "is_stable"], axis=1)

方式2:向量化操作(高效处理大数据)

# 生成相邻差值达标布尔掩码
diff_mask = df["value"].diff().abs() < 0.005
# 扩展掩码:保留连续达标段的所有点,包括段内第一个点
stable_mask = diff_mask.cumsum().where(diff_mask, 0) != 0
# 单独处理第一个点:若第二个点与它差值达标则保留
if diff_mask.iloc[0]:
    stable_mask.iloc[0] = True

stable_points = df[stable_mask]

2. 绘制稳定点

用matplotlib可视化,可选叠加原始数据做对比:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
# 绘制原始数据(透明度降低作为背景)
plt.plot(df["time"], df["value"], color="#cccccc", label="Original Data", alpha=0.6)
# 绘制稳定点(红色散点突出显示)
plt.scatter(stable_points["time"], stable_points["value"], color="#ff4444", label="Stable Points", s=12)

plt.xlabel("Time")
plt.ylabel("Value")
plt.title("Stable Points in Time Series")
plt.legend()
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.show()

3. 稳定点的线性回归

用scikit-learn实现线性拟合,输出模型参数并可视化回归直线:

from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

# 准备模型输入数据(sklearn要求特征为二维数组)
X = stable_points["time"].values.reshape(-1, 1)
y = stable_points["value"].values.reshape(-1, 1)

# 训练线性回归模型
reg_model = LinearRegression()
reg_model.fit(X, y)

# 生成预测值
y_pred = reg_model.predict(X)

# 输出模型结果
print(f"回归方程: y = {reg_model.coef_[0][0]:.4f} * time + {reg_model.intercept_[0]:.4f}")
print(f"模型R²得分: {r2_score(y, y_pred):.4f}")

# 可视化回归结果
plt.figure(figsize=(10, 6))
plt.scatter(stable_points["time"], stable_points["value"], color="#ff4444", label="Stable Points", s=12)
plt.plot(stable_points["time"], y_pred, color="#0066cc", label="Regression Line", linewidth=2)

plt.xlabel("Time")
plt.ylabel("Value")
plt.title("Linear Regression on Stable Points")
plt.legend()
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.show()

进阶处理:多稳定段单独拟合

如果数据包含多个独立稳定段(中间被过渡阶段隔开),可以按段分组后单独执行回归:

# 给稳定点分组:当相邻值突变时,划分新段
stable_points["segment_id"] = (stable_points["value"].diff().abs() >= 0.005).cumsum()

# 遍历每个稳定段拟合回归
for seg_id, seg_data in stable_points.groupby("segment_id"):
    X_seg = seg_data["time"].values.reshape(-1, 1)
    y_seg = seg_data["value"].values.reshape(-1, 1)
    
    seg_model = LinearRegression()
    seg_model.fit(X_seg, y_seg)
    
    r2 = r2_score(y_seg, seg_model.predict(X_seg))
    print(f"Segment {seg_id}: y = {seg_model.coef_[0][0]:.4f}*time + {seg_model.intercept_[0]:.4f}, R²={r2:.4f}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:12:25