python 时间序列的趋势聚类算法-基于斜率的趋势聚类 - cluster_centers_

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网 👁️ 593 次阅读

问题引出:针对时间序列提取部分趋势问题,例如提取波动时间序列的上升趋势过程及下降趋势过程中存在阈值提取过于呆板,不够灵活拟合完整趋势问题,多次相似趋势具体不同时无法共用同一阈值。 拼多多帮助力入口

问题解决:针对上述提出的问题,现在提出基于求时间序列的斜率,然后通过K-means进行聚类对时间序列斜率进行聚类展示相似趋势。

import numpy as np

from sklearn.cluster import KMeans

import matplotlib.pyplot as plt

from scipy.signal import savgol_filter

# 示例:生成一些模拟时间序列数据

np.random.seed(0)

time_points = np.linspace(0, 10, 100)

data = np.sin(time_points) + np.random.normal(0, 0.1, size=time_points.shape)

# 平滑处理

window_length = 11 # 必须为正奇数

polyorder = 2 # 多项式拟合的阶数

smoothed_data = savgol_filter(data, window_length=window_length, polyorder=polyorder)

# 计算相邻点之间的斜率

slopes = np.diff(smoothed_data) / np.diff(time_points)

# 为了便于聚类,我们将斜率转换为二维数组格式

slopes_reshaped = slopes.reshape(-1, 1)

# 使用KMeans进行聚类

n_clusters = 3 # 根据实际情况选择合适的簇数

kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(slopes_reshaped)

# 获取每个斜率对应的簇标签

labels = kmeans.labels_

# 打印每个簇的中心斜率值

print("Cluster Centers (Slopes):", kmeans.cluster_centers_.flatten())

# 可视化结果

plt.figure(figsize=(14, 5))

# 原始数据和平滑后数据对比

plt.plot(time_points, data, label='Original Data', alpha=0.5)

plt.plot(time_points, smoothed_data, label='Smoothed Data')

# 显示基于斜率聚类的结果

for i in range(n_clusters):

mask = labels == i

plt.plot(time_points[1:][mask], smoothed_data[1:][mask], 'o', label=f'Cluster {i} Slope')

plt.title('Data Grouped by Similar Slopes after Smoothing')

plt.xlabel('Time')

plt.ylabel('Value')

plt.legend()

plt.show()

python 时间序列的趋势聚类算法-基于斜率的趋势聚类

推荐链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧