欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用tslearn库在Python中进行时间序列聚类和可视化

最编程 2024-01-19 15:00:51
...

我们最近在完成一些时间序列聚类任务,偶然发现了 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)

这里有一些很好的例子:

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

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

Python用 tslearn 进行时间序列聚类可视化_数据_03

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

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

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


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