打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python用 tslearn 进行时间序列聚类可视化

全文链接:https://tecdat.cn/?p=33484

我们最近在完成一些时间序列聚类任务,偶然发现了 tslearn 库。我很想看看启动和运行 tslearn 已内置的聚类有多简单,结果发现非常简单直接点击文末“阅读原文”获取完整代码数据

相关视频

首先,让我们导入我们需要的库:


import pandas as pd
import numpy as np

from tslearn.preprocessing import TimeSeriesScalerMeanVariance

netdata_pandas 用于提取一些时间序列数据到 pandas 数据框中。

plots为我添加了常用的绘图功能,我发现自己一次又一次地回到了这个库中。

我们定义输入,基本上任何我们可以使用和更改的东西都值得作为输入添加到笔记本的顶部:


n_clusters = 50 # number of clusters to fit

smooth_n = 15 # n observations to smooth over

model = 'kmeans' # one of ['kmeans','kshape','kernelkmeans','dtw']

接下来,我们将获取数据并进行一些标准的预处理:


if n_charts:
charts = np.random.choice(get_chart_list(host), n_charts).tolist()
print(charts)
else:
charts = get_chart_list(host)
# get data
df = get_data(host, charts, after=-n, before=0)

if smooth_n > 0:
if smooth_func == 'mean':
df = df.rolling(smooth_n).mean().dropna(how='all')
elif smooth_func == 'max':
df = df.rolling(smooth_n).max().dropna(how='all')
elif smooth_func == 'min':
df = df.rolling(smooth_n).min().dropna(how='all')
elif smooth_func == 'sum':
df = df.rolling(smooth_n).sum().dropna(how='all')
else:
df = df.rolling(smooth_n).mean().dropna(how='all')

print(df.shape)
df.head()

然后用 tslearn 建立我们的聚类模型了:




if model == 'kshape':
model = KShape(n_clusters=n_clusters, max_iter=10, n_init=2).fit(X)
elif model == 'kmeans':
model = TimeSeriesKMeans(n_clusters=n_clusters,

有了聚类集群后,我们就可以制作一些辅助对象供以后使用:



cluster_metrics_dict = df_cluster.groupby(['cluster'])['metric'].apply(lambda x: [x for x in x]).to_dict()
cluster_len_dict = df_cluster['cluster'].value_counts().to_dict()

clusters_final.sort()

df_cluster.head()

最后,让我们分别绘制每个聚类群组,看看有什么结果:


for cluster_number in clusters_final:

x_corr = df[cluster_metrics_dict[cluster_number]].corr().abs().values

plot_lines(df, cols=cluster_metrics_dict[cluster_number], renderer='colab', theme=None, title=plot_title)

这里有一些很好的例子:


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python时间序列分析库介绍:statsmodels、tslearn、tssearch、tsfresh
推荐 3 个 Python 时序分析神器
qlib智能量化里的"因子分析",“多空分析”
Pandas入门教程
逐步深入绘制热图
R语言学习笔记之热图绘制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服