欢迎光临散文网 会员登陆 & 注册

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

2023-08-25 00:19 作者:拓端tecdat  | 我要投稿

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

原文出处:拓端数据部落公众号

我们最近在完成一些时间序列聚类任务,偶然发现了 tslearn 库。我很想看看启动和运行 tslearn 已内置的聚类有多简单,结果发现非常简单直接。

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

import pandas as pdimport numpy as npfrom tslearn.preprocessing import TimeSeriesScalerMeanVariance

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

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

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

n_clusters = 50 # number of clusters to fitsmooth_n = 15 # n observations to smooth overmodel = '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 datadf = 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)

这里有一些很好的例子:

聚类的典型特征是你总是会得到一些看起来很糟糕的随机数据,尤其是因为我真的是凭空选取了上面的很多参数,最重要的是 K 聚类的数量,鉴于我们有大量的指标(超过 700 个),我将其设置为 50 个。

总之,我发现 tslearn 库非常有用,因为它节省了我很多时间,让我快速建立并运行了一个工作原型,所以我期待着还能使用它提供的其他一些时间序列相关功能。

最受欢迎的见解

1.在python中使用lstm和pytorch进行时间序列预测

2.python中利用长短期记忆模型lstm进行时间序列预测分析

3.Python用RNN循环神经网络:LSTM长期记忆、GRU门循环单元、回归和ARIMA对COVID-19新冠疫情新增人数时间序列

4.Python TensorFlow循环神经网络RNN-LSTM神经网络预测股票市场价格时间序列和MSE评估准确性

5.r语言copulas和金融时间序列案例

6.R 语言用RNN循环神经网络 、LSTM长短期记忆网络实现时间序列长期利率预测

7.Matlab创建向量自回归(VAR)模型分析消费者价格指数 (CPI) 和失业率时间序列

8.r语言k-shape时间序列聚类方法对股票价格时间序列聚类

9.R语言结合新冠疫情COVID-19股票价格预测:ARIMA,KNN和神经网络时间序列分析


Python用 tslearn 进行时间序列聚类可视化的评论 (共 条)

分享到微博请遵守国家法律