Python用 tslearn 進(jìn)行時(shí)間序列聚類可視化
全文鏈接:https://tecdat.cn/?p=33484
原文出處:拓端數(shù)據(jù)部落公眾號(hào)
我們最近在完成一些時(shí)間序列聚類任務(wù),偶然發(fā)現(xiàn)了 tslearn 庫。我很想看看啟動(dòng)和運(yùn)行 tslearn 已內(nèi)置的聚類有多簡單,結(jié)果發(fā)現(xiàn)非常簡單直接。
首先,讓我們導(dǎo)入我們需要的庫:
import pandas as pdimport numpy as npfrom tslearn.preprocessing import TimeSeriesScalerMeanVariance
netdata_pandas 用于提取一些時(shí)間序列數(shù)據(jù)到 pandas 數(shù)據(jù)框中。
plots為我添加了常用的繪圖功能,我發(fā)現(xiàn)自己一次又一次地回到了這個(gè)庫中。
我們定義輸入,基本上任何我們可以使用和更改的東西都值得作為輸入添加到筆記本的頂部:
n_clusters = 50 # number of clusters to fitsmooth_n = 15 # n observations to smooth overmodel = 'kmeans' # one of ['kmeans','kshape','kernelkmeans','dtw']
接下來,我們將獲取數(shù)據(jù)并進(jìn)行一些標(biāo)準(zhǔn)的預(yù)處理:
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()
最后,讓我們分別繪制每個(gè)聚類群組,看看有什么結(jié)果:
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)
這里有一些很好的例子:




聚類的典型特征是你總是會(huì)得到一些看起來很糟糕的隨機(jī)數(shù)據(jù),尤其是因?yàn)槲艺娴氖菓{空選取了上面的很多參數(shù),最重要的是 K 聚類的數(shù)量,鑒于我們有大量的指標(biāo)(超過 700 個(gè)),我將其設(shè)置為 50 個(gè)。
總之,我發(fā)現(xiàn) tslearn 庫非常有用,因?yàn)樗?jié)省了我很多時(shí)間,讓我快速建立并運(yùn)行了一個(gè)工作原型,所以我期待著還能使用它提供的其他一些時(shí)間序列相關(guān)功能。

最受歡迎的見解
1.在python中使用lstm和pytorch進(jìn)行時(shí)間序列預(yù)測
2.python中利用長短期記憶模型lstm進(jìn)行時(shí)間序列預(yù)測分析
3.Python用RNN循環(huán)神經(jīng)網(wǎng)絡(luò):LSTM長期記憶、GRU門循環(huán)單元、回歸和ARIMA對COVID-19新冠疫情新增人數(shù)時(shí)間序列
4.Python TensorFlow循環(huán)神經(jīng)網(wǎng)絡(luò)RNN-LSTM神經(jīng)網(wǎng)絡(luò)預(yù)測股票市場價(jià)格時(shí)間序列和MSE評估準(zhǔn)確性
5.r語言copulas和金融時(shí)間序列案例
6.R 語言用RNN循環(huán)神經(jīng)網(wǎng)絡(luò) 、LSTM長短期記憶網(wǎng)絡(luò)實(shí)現(xiàn)時(shí)間序列長期利率預(yù)測
7.Matlab創(chuàng)建向量自回歸(VAR)模型分析消費(fèi)者價(jià)格指數(shù) (CPI) 和失業(yè)率時(shí)間序列
8.r語言k-shape時(shí)間序列聚類方法對股票價(jià)格時(shí)間序列聚類
9.R語言結(jié)合新冠疫情COVID-19股票價(jià)格預(yù)測:ARIMA,KNN和神經(jīng)網(wǎng)絡(luò)時(shí)間序列分析