AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當(dāng)前位置:首頁 > 科技  > 軟件

使用輪廓分?jǐn)?shù)提升時間序列聚類的表現(xiàn)

來源: 責(zé)編: 時間:2023-10-16 17:07:09 228觀看
導(dǎo)讀我們將使用輪廓分?jǐn)?shù)和一些距離指標(biāo)來執(zhí)行時間序列聚類實(shí)驗(yàn),并且進(jìn)行可視化讓我們看看下面的時間序列:如果沿著y軸移動序列添加隨機(jī)噪聲,并隨機(jī)化這些序列,那么它們幾乎無法分辨,如下圖所示-現(xiàn)在很難將時間序列列分組為簇:

我們將使用輪廓分?jǐn)?shù)和一些距離指標(biāo)來執(zhí)行時間序列聚類實(shí)驗(yàn),并且進(jìn)行可視化T4v28資訊網(wǎng)——每日最新資訊28at.com

讓我們看看下面的時間序列:T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

如果沿著y軸移動序列添加隨機(jī)噪聲,并隨機(jī)化這些序列,那么它們幾乎無法分辨,如下圖所示-現(xiàn)在很難將時間序列列分組為簇:T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

上面的圖表是使用以下腳本創(chuàng)建的:T4v28資訊網(wǎng)——每日最新資訊28at.com

# Import necessary libraries import os import pandas as pd import numpy as np  # Import random module with an alias 'rand' import random as rand from scipy import signal  # Import the matplotlib library for plotting import matplotlib.pyplot as plt  # Generate an array 'x' ranging from 0 to 5*pi with a step of 0.1 x = np.arange(0, 5*np.pi, 0.1)  # Generate square, sawtooth, sin, and cos waves based on 'x' y_square = signal.square(np.pi * x) y_sawtooth = signal.sawtooth(np.pi * x) y_sin = np.sin(x) y_cos = np.cos(x)  # Create a DataFrame 'df_waves' to store the waveforms df_waves = pd.DataFrame([x, y_sawtooth, y_square, y_sin, y_cos]).transpose()  # Rename the columns of the DataFrame for clarity df_waves = df_waves.rename(columns={0: 'time',                                    1: 'sawtooth',                                    2: 'square',                                    3: 'sin',                                    4: 'cos'})  # Plot the original waveforms against time df_waves.plot(x='time', legend=False) plt.show()  # Add noise to the waveforms and plot them again for col in df_waves.columns:    if col != 'time':        for i in range(1, 10):            # Add noise to each waveform based on 'i' and a random value            df_waves['{}_{}'.format(col, i)] = df_waves[col].apply(lambda x: x + i + rand.random() * 0.25 * i)  # Plot the waveforms with added noise against time df_waves.plot(x='time', legend=False) plt.show()

現(xiàn)在我們需要確定聚類的基礎(chǔ)。這里有兩種方法:T4v28資訊網(wǎng)——每日最新資訊28at.com

把接近于一組的波形分組——較低歐幾里得距離的波形將聚在一起。T4v28資訊網(wǎng)——每日最新資訊28at.com

把看起來相似的波形分組——它們有相似的形狀,但歐幾里得距離可能不低。T4v28資訊網(wǎng)——每日最新資訊28at.com

距離度量

一般來說,我們希望根據(jù)形狀對時間序列進(jìn)行分組,對于這樣的聚類-可能希望使用距離度量,如相關(guān)性,這些度量或多或少與波形的線性移位無關(guān)。T4v28資訊網(wǎng)——每日最新資訊28at.com

讓我們看看上面定義的帶有噪聲的波形對之間的歐幾里得距離和相關(guān)性的熱圖:T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

可以看到歐幾里得距離對波形進(jìn)行分組是很困難的,因?yàn)槿魏我唤M波形對的模式都是相似的。例如,除了對角線元素外,square & cos之間的相關(guān)形狀與square和square之間的相關(guān)形狀非常相似T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

所有的形狀都可以很容易地使用相關(guān)熱圖組合在一起——因?yàn)轭愃频牟ㄐ尉哂蟹浅8叩南嚓P(guān)性(sin-sin對),而像sin和cos這樣的波形幾乎沒有相關(guān)性。T4v28資訊網(wǎng)——每日最新資訊28at.com

輪廓分?jǐn)?shù)

通過上面熱圖和分析,根據(jù)高相關(guān)性分配組看起來是一個好主意,但是我們?nèi)绾味x相關(guān)閾值呢?看起來像一個迭代過程,容易出現(xiàn)不準(zhǔn)確和大量的人工工作。T4v28資訊網(wǎng)——每日最新資訊28at.com

在這種情況下,我們可以使用輪廓分?jǐn)?shù)(Silhouette score),它為執(zhí)行的聚類分配一個分?jǐn)?shù)。我們的目標(biāo)是使輪廓分?jǐn)?shù)最大化。T4v28資訊網(wǎng)——每日最新資訊28at.com

輪廓分?jǐn)?shù)(Silhouette Score)是一種用于評估聚類質(zhì)量的指標(biāo),它可以幫助你確定數(shù)據(jù)點(diǎn)是否被正確地分配到它們的簇中。較高的輪廓分?jǐn)?shù)表示簇內(nèi)數(shù)據(jù)點(diǎn)相互之間更加相似,而不同簇之間的數(shù)據(jù)點(diǎn)差異更大,這通常是良好的聚類結(jié)果。T4v28資訊網(wǎng)——每日最新資訊28at.com

輪廓分?jǐn)?shù)的計算方法如下:T4v28資訊網(wǎng)——每日最新資訊28at.com

  1. 對于每個數(shù)據(jù)點(diǎn) i,計算以下兩個值:
  • a(i):數(shù)據(jù)點(diǎn) i 到同一簇中所有其他點(diǎn)的平均距離(簇內(nèi)平均距離)。
  • b(i):數(shù)據(jù)點(diǎn) i 到與其不同簇中的所有簇的平均距離,取最小值(最近簇的平均距離)。
  1. 然后,計算每個數(shù)據(jù)點(diǎn)的輪廓系數(shù) s(i),它定義為:s(i) = /frac{b(i) - a(i)}{/max/{a(i), b(i)/}}
  2. 最后,計算整個數(shù)據(jù)集的輪廓分?jǐn)?shù),它是所有數(shù)據(jù)點(diǎn)的輪廓系數(shù)的平均值:/text{輪廓分?jǐn)?shù)} = /frac{1}{N} /sum_{i=1}^{N} s(i)

其中,N 是數(shù)據(jù)點(diǎn)的總數(shù)。T4v28資訊網(wǎng)——每日最新資訊28at.com

輪廓分?jǐn)?shù)的取值范圍在 -1 到 1 之間,具體含義如下:T4v28資訊網(wǎng)——每日最新資訊28at.com

  • 輪廓分?jǐn)?shù)接近1:表示簇內(nèi)數(shù)據(jù)點(diǎn)相似度高,不同簇之間的差異很大,是一個好的聚類結(jié)果。
  • 輪廓分?jǐn)?shù)接近0:表示數(shù)據(jù)點(diǎn)在簇內(nèi)的相似度與簇間的差異相當(dāng),可能是重疊的聚類或者不明顯的聚類。
  • 輪廓分?jǐn)?shù)接近-1:表示數(shù)據(jù)點(diǎn)更適合分配到其他簇,不同簇之間的差異相比簇內(nèi)差異更小,通常是一個糟糕的聚類結(jié)果。

一些重要的知識點(diǎn):T4v28資訊網(wǎng)——每日最新資訊28at.com

在所有點(diǎn)上的高平均輪廓分?jǐn)?shù)(接近1)表明簇的定義良好且明顯。T4v28資訊網(wǎng)——每日最新資訊28at.com

低或負(fù)的平均輪廓分?jǐn)?shù)(接近-1)表明重疊或形成不良的集群。T4v28資訊網(wǎng)——每日最新資訊28at.com

0左右的分?jǐn)?shù)表示該點(diǎn)位于兩個簇的邊界上。T4v28資訊網(wǎng)——每日最新資訊28at.com

聚類

現(xiàn)在讓我們嘗試對時間序列進(jìn)行分組。我們已經(jīng)知道存在四種不同的波形,因此理想情況下應(yīng)該有四個簇。T4v28資訊網(wǎng)——每日最新資訊28at.com

歐氏距離

pca = decomposition.PCA(n_compnotallow=2) pca.fit(df_man_dist_euc) df_fc_cleaned_reduced_euc = pd.DataFrame(pca.transform(df_man_dist_euc).transpose(),                                               index = ['PC_1','PC_2'],                                              columns = df_man_dist_euc.transpose().columns)  index = 0 range_n_clusters = [2, 3, 4, 5, 6, 7, 8]  # Iterate over different cluster numbers for n_clusters in range_n_clusters:    # Create a subplot with silhouette plot and cluster visualization    fig, (ax1, ax2) = plt.subplots(1, 2)    fig.set_size_inches(15, 7)     # Set the x and y axis limits for the silhouette plot    ax1.set_xlim([-0.1, 1])    ax1.set_ylim([0, len(df_man_dist_euc) + (n_clusters + 1) * 10])     # Initialize the KMeans clusterer with n_clusters and random seed    clusterer = KMeans(n_clusters=n_clusters, n_init="auto", random_state=10)    cluster_labels = clusterer.fit_predict(df_man_dist_euc)     # Calculate silhouette score for the current cluster configuration    silhouette_avg = silhouette_score(df_man_dist_euc, cluster_labels)    print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg)    sil_score_results.loc[index, ['number_of_clusters', 'Euclidean']] = [n_clusters, silhouette_avg]    index += 1         # Calculate silhouette values for each sample    sample_silhouette_values = silhouette_samples(df_man_dist_euc, cluster_labels)         y_lower = 10     # Plot the silhouette plot    for i in range(n_clusters):        # Aggregate silhouette scores for samples in the cluster and sort them        ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]        ith_cluster_silhouette_values.sort()         # Set the y_upper value for the silhouette plot        size_cluster_i = ith_cluster_silhouette_values.shape[0]        y_upper = y_lower + size_cluster_i         color = cm.nipy_spectral(float(i) / n_clusters)         # Fill silhouette plot for the current cluster        ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7)         # Label the silhouette plot with cluster numbers        ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))        y_lower = y_upper + 10 # Update y_lower for the next plot     # Set labels and title for the silhouette plot    ax1.set_title("The silhouette plot for the various clusters.")    ax1.set_xlabel("The silhouette coefficient values")    ax1.set_ylabel("Cluster label")     # Add vertical line for the average silhouette score    ax1.axvline(x=silhouette_avg, color="red", linestyle="--")    ax1.set_yticks([]) # Clear the yaxis labels / ticks    ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])     # Plot the actual clusters    colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)    ax2.scatter(df_fc_cleaned_reduced_euc.transpose().iloc[:, 0], df_fc_cleaned_reduced_euc.transpose().iloc[:, 1],                marker=".", s=30, lw=0, alpha=0.7, c=colors, edgecolor="k")     # Label the clusters and cluster centers    centers = clusterer.cluster_centers_    ax2.scatter(centers[:, 0], centers[:, 1], marker="o", c="white", alpha=1, s=200, edgecolor="k")     for i, c in enumerate(centers):        ax2.scatter(c[0], c[1], marker="$%d$" % i, alpha=1, s=50, edgecolor="k")     # Set labels and title for the cluster visualization    ax2.set_title("The visualization of the clustered data.")    ax2.set_xlabel("Feature space for the 1st feature")    ax2.set_ylabel("Feature space for the 2nd feature")     # Set the super title for the whole plot    plt.suptitle("Silhouette analysis for KMeans clustering on sample data with n_clusters = %d" % n_clusters,                  fnotallow=14, fnotallow="bold")  plt.savefig('sil_score_eucl.png') plt.show()

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

可以看到無論分成多少簇,數(shù)據(jù)都是混合的,并不能為任何數(shù)量的簇提供良好的輪廓分?jǐn)?shù)。這與我們基于歐幾里得距離熱圖的初步評估的預(yù)期一致T4v28資訊網(wǎng)——每日最新資訊28at.com

相關(guān)性

pca = decomposition.PCA(n_compnotallow=2) pca.fit(df_man_dist_corr) df_fc_cleaned_reduced_corr = pd.DataFrame(pca.transform(df_man_dist_corr).transpose(),                                               index = ['PC_1','PC_2'],                                              columns = df_man_dist_corr.transpose().columns)  index=0 range_n_clusters = [2,3,4,5,6,7,8] for n_clusters in range_n_clusters:    # Create a subplot with 1 row and 2 columns    fig, (ax1, ax2) = plt.subplots(1, 2)    fig.set_size_inches(15, 7)     # The 1st subplot is the silhouette plot    # The silhouette coefficient can range from -1, 1 but in this example all    # lie within [-0.1, 1]    ax1.set_xlim([-0.1, 1])    # The (n_clusters+1)*10 is for inserting blank space between silhouette    # plots of individual clusters, to demarcate them clearly.    ax1.set_ylim([0, len(df_man_dist_corr) + (n_clusters + 1) * 10])     # Initialize the clusterer with n_clusters value and a random generator    # seed of 10 for reproducibility.    clusterer = KMeans(n_clusters=n_clusters, n_init="auto", random_state=10)    cluster_labels = clusterer.fit_predict(df_man_dist_corr)     # The silhouette_score gives the average value for all the samples.    # This gives a perspective into the density and separation of the formed    # clusters    silhouette_avg = silhouette_score(df_man_dist_corr, cluster_labels)    print(        "For n_clusters =",        n_clusters,        "The average silhouette_score is :",        silhouette_avg,    )    sil_score_results.loc[index,['number_of_clusters','corrlidean']] = [n_clusters,silhouette_avg]    index=index+1         sample_silhouette_values = silhouette_samples(df_man_dist_corr, cluster_labels)         y_lower = 10    for i in range(n_clusters):        # Aggregate the silhouette scores for samples belonging to        # cluster i, and sort them        ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]         ith_cluster_silhouette_values.sort()         size_cluster_i = ith_cluster_silhouette_values.shape[0]        y_upper = y_lower + size_cluster_i         color = cm.nipy_spectral(float(i) / n_clusters)        ax1.fill_betweenx(            np.arange(y_lower, y_upper),            0,            ith_cluster_silhouette_values,            facecolor=color,            edgecolor=color,            alpha=0.7,        )         # Label the silhouette plots with their cluster numbers at the middle        ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))         # Compute the new y_lower for next plot        y_lower = y_upper + 10 # 10 for the 0 samples     ax1.set_title("The silhouette plot for the various clusters.")    ax1.set_xlabel("The silhouette coefficient values")    ax1.set_ylabel("Cluster label")     # The vertical line for average silhouette score of all the values    ax1.axvline(x=silhouette_avg, color="red", linestyle="--")     ax1.set_yticks([]) # Clear the yaxis labels / ticks    ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])     # 2nd Plot showing the actual clusters formed    colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)         ax2.scatter(        df_fc_cleaned_reduced_corr.transpose().iloc[:, 0],         df_fc_cleaned_reduced_corr.transpose().iloc[:, 1], marker=".", s=30, lw=0, alpha=0.7, c=colors, edgecolor="k"    )      #     for i in range(len(df_fc_cleaned_cleaned_reduced.transpose().iloc[:, 0])): #                         ax2.annotate(list(df_fc_cleaned_cleaned_reduced.transpose().index)[i],  #                                     (df_fc_cleaned_cleaned_reduced.transpose().iloc[:, 0][i],  #                                       df_fc_cleaned_cleaned_reduced.transpose().iloc[:, 1][i] + 0.2))             # Labeling the clusters    centers = clusterer.cluster_centers_    # Draw white circles at cluster centers    ax2.scatter(        centers[:, 0],        centers[:, 1],        marker="o",        c="white",        alpha=1,        s=200,        edgecolor="k",    )     for i, c in enumerate(centers):        ax2.scatter(c[0], c[1], marker="$%d$" % i, alpha=1, s=50, edgecolor="k")     ax2.set_title("The visualization of the clustered data.")    ax2.set_xlabel("Feature space for the 1st feature")    ax2.set_ylabel("Feature space for the 2nd feature")     plt.suptitle(        "Silhouette analysis for KMeans clustering on sample data with n_clusters = %d"        % n_clusters,        fnotallow=14,        fnotallow="bold",    )  plt.show()

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

T4v28資訊網(wǎng)——每日最新資訊28at.com

當(dāng)選擇的簇數(shù)為4時,我們可以清楚地看到分離的簇,其他結(jié)果通常比歐氏距離要好得多。T4v28資訊網(wǎng)——每日最新資訊28at.com

歐幾里得距離與相關(guān)廓形評分的比較

T4v28資訊網(wǎng)——每日最新資訊28at.com

輪廓分?jǐn)?shù)表明基于相關(guān)性的距離矩陣在簇數(shù)為4時效果最好,而在歐氏距離的情況下效果就不那么明顯了結(jié)論T4v28資訊網(wǎng)——每日最新資訊28at.com

總結(jié)

在本文中,我們研究了如何使用歐幾里得距離和相關(guān)度量執(zhí)行時間序列聚類,并觀察了這兩種情況下的結(jié)果如何變化。如果我們在評估聚類時結(jié)合Silhouette,我們可以使聚類步驟更加客觀,因?yàn)樗峁┝艘环N很好的直觀方式來查看聚類的分離情況。T4v28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-13365-0.html使用輪廓分?jǐn)?shù)提升時間序列聚類的表現(xiàn)

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: C++編程入門!五個學(xué)習(xí)階段讓你從新手到高手

下一篇: Python開發(fā)利器:掌握PyCharm的精髓

標(biāo)簽:
  • 熱門焦點(diǎn)
  • 一加Ace2 Pro真機(jī)揭曉 鈦空灰配色質(zhì)感拉滿

    終于,在經(jīng)過了幾波預(yù)熱之后,一加Ace2 Pro的外觀真機(jī)圖在網(wǎng)上出現(xiàn)了。還是博主數(shù)碼閑聊站曝光的,這次的外觀設(shè)計還是延續(xù)了一加11的方案,只是細(xì)節(jié)上有了調(diào)整,例如新加入了鈦空灰
  • 俄羅斯:將審查iPhone等外國公司設(shè)備 保數(shù)據(jù)安全

    iPhone和特斯拉都屬于在各自領(lǐng)域領(lǐng)頭羊的品牌,推出的產(chǎn)品也也都是數(shù)一數(shù)二的,但對于一些國家而言,它們的產(chǎn)品可靠性和安全性還是在限制范圍內(nèi)。近日,俄羅斯聯(lián)邦通信、信息技術(shù)
  • Redmi Buds 4開箱簡評:才199還有降噪 可以無腦入

    在上個月舉辦的Redmi Note11T Pro系列新機(jī)發(fā)布會上,除了兩款手機(jī)新品之外,Redmi還帶來了兩款TWS真無線藍(lán)牙耳機(jī)產(chǎn)品,Redmi Buds 4和Redmi Buds 4 Pro,此前我們在Redmi Note11T
  • 6月iOS設(shè)備性能榜:M2穩(wěn)居榜首 A系列只能等一手3nm來救

    沒有新品發(fā)布,自然iOS設(shè)備性能榜的上榜設(shè)備就沒有什么更替,僅僅只有跑分變化而產(chǎn)生的排名變動,畢竟蘋果新品的發(fā)布節(jié)奏就是這樣的,一年下來也就幾個移動端新品,不會像安卓廠商,一
  • 如何通過Python線程池實(shí)現(xiàn)異步編程?

    線程池的概念和基本原理線程池是一種并發(fā)處理機(jī)制,它可以在程序啟動時創(chuàng)建一組線程,并將它們置于等待任務(wù)的狀態(tài)。當(dāng)任務(wù)到達(dá)時,線程池中的某個線程會被喚醒并執(zhí)行任務(wù),執(zhí)行完任
  • 三言兩語說透柯里化和反柯里化

    JavaScript中的柯里化(Currying)和反柯里化(Uncurrying)是兩種很有用的技術(shù),可以幫助我們寫出更加優(yōu)雅、泛用的函數(shù)。本文將首先介紹柯里化和反柯里化的概念、實(shí)現(xiàn)原理和應(yīng)用
  • 得物寵物生意「狂飆」,發(fā)力“它經(jīng)濟(jì)”

    作者|花花小萌主近日,得物宣布正式上線寵物鑒別,通過得物App內(nèi)的“在線鑒別”,可找到鑒別寵物的選項(xiàng)。通過上傳自家寵物的部位細(xì)節(jié),就能收獲擁有專業(yè)資質(zhì)認(rèn)證的得物鑒
  • 品牌洞察丨服務(wù)本地,美團(tuán)直播成效幾何?

    來源:17PR7月11日,美團(tuán)App首頁推薦位出現(xiàn)“美團(tuán)直播”的固定入口。在直播聚合頁面,外賣“神槍手”直播間、美團(tuán)旅行直播間、美團(tuán)買菜直播間等均已上線,同時
  • DRAM存儲器10月價格下跌,NAND閃存本月價格與上月持平

    10月30日,據(jù)韓國媒體消息,自今年年初以來一直在上漲的 DRAM 存儲器的交易價格僅在本月就下跌了近 10%,此次是全年首次降價,而NAND 閃存本月價格與上月持平。市
Top