Python實現(xiàn)多維數(shù)據(jù)分析的示例詳解
多維數(shù)據(jù)分析是對數(shù)據(jù)的信息分析,它考慮了許多關(guān)系。讓我們來介紹一些使用Python分析多維/多變量數(shù)據(jù)的基本技術(shù)。
從這里找到用于說明的數(shù)據(jù)的鏈接。(https://archive.ics.uci.edu/dataset/111/zoo)
以下代碼用于從zoo_data. csv讀取2D表格數(shù)據(jù)。
import pandas as pd
zoo_data = pd.read_csv("zoo_data.csv", encoding = 'utf-8',
index_col = ["animal_name"])
# print first 5 rows of zoo data
print(zoo_data.head())
輸出

**注意:**我們這里的數(shù)據(jù)類型通常是分類的。本案例研究中使用的分類數(shù)據(jù)分析技術(shù)是非?;镜?,易于理解,解釋和實施。這些方法包括聚類分析、相關(guān)分析、PCA(主成分分析)和EDA(探索性數(shù)據(jù)分析)。
聚類分析
由于我們擁有的數(shù)據(jù)是基于不同類型動物的特征,我們可以使用一些眾所周知的聚類技術(shù)將動物分為不同的組(簇)或子組,即KMeans聚類,DBscan,層次聚類和KNN(K-Nearest Neighbours)聚類。為了簡單起見,在這種情況下,KMeans聚類應(yīng)該是一個更好的選擇。使用Kmeans聚類技術(shù)對數(shù)據(jù)進(jìn)行聚類,可以使用sklearn庫聚類類的KMeans模塊實現(xiàn),如下所示:
# from sklearn.cluster import KMeans clusters = 7 kmeans = KMeans(n_clusters = clusters) kmeans.fit(zoo_data) print(kmeans.labels_)
輸出

inertia表示的是每個樣本點到其所在質(zhì)心的距離之和。按照inertia的定義來說inertia是越小越好。
在這里,總的集群inertia是119.70392382759556。
EDA分析
為了執(zhí)行EDA分析,我們需要將多變量數(shù)據(jù)降維為三變量/雙變量(2D/3D)數(shù)據(jù)。我們可以使用PCA(主成分分析)來實現(xiàn)這個任務(wù)。
可以使用sklearn庫的類分解的PCA模塊進(jìn)行PCA,如下所示:
# from sklearn.decomposition import PCA pca = PCA(3) pca.fit(zoo_data) pca_data = pd.DataFrame(pca.transform(zoo_data)) print(pca_data.head())
輸出

上面的數(shù)據(jù)輸出表示簡化的三變量(3D)數(shù)據(jù),我們可以在其上執(zhí)行EDA分析。
注意: PCA產(chǎn)生的簡化數(shù)據(jù)可間接用于執(zhí)行各種分析,但不能直接由人類解釋。
散點圖是一種2D/3D圖,有助于分析2D/3D數(shù)據(jù)中的各種聚類。
我們之前制作的3D簡化數(shù)據(jù)的散點圖可以繪制如下:
下面的代碼是一個Python代碼,它生成一個顏色數(shù)組(其中顏色的數(shù)量大約等于聚類的數(shù)量),按照色調(diào),值和飽和度值的順序進(jìn)行排序。這里,每種顏色與單個聚類相關(guān)聯(lián),并將用于將動物表示為3D點,同時將其繪制在3D圖/空間中(本例中為散點圖)。
from matplotlib import colors as mcolors import math ''' Generating different colors in ascending order of their hsv values ''' colors = list(zip(*sorted(( tuple(mcolors.rgb_to_hsv( mcolors.to_rgba(color)[:3])), name) for name, color in dict( mcolors.BASE_COLORS, **mcolors.CSS4_COLORS ).items())))[1] # number of steps to taken generate n(clusters) colors skips = math.floor(len(colors[5 : -5])/clusters) cluster_colors = colors[5 : -5 : skips]
下面的代碼是一個pythonic代碼,它生成一個3D散點圖,其中每個數(shù)據(jù)點都有一個與其對應(yīng)的聚類相關(guān)的顏色。
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') ax.scatter(pca_data[0], pca_data[1], pca_data[2], c = list(map(lambda label : cluster_colors[label], kmeans.labels_))) str_labels = list(map(lambda label:'% s' % label, kmeans.labels_)) list(map(lambda data1, data2, data3, str_label: ax.text(data1, data2, data3, s = str_label, size = 16.5, zorder = 20, color = 'k'), pca_data[0], pca_data[1], pca_data[2], str_labels)) plt.show()
輸出

仔細(xì)分析散點圖可以得出這樣的假設(shè),即使用初始數(shù)據(jù)形成的聚類沒有足夠好的解釋力。為了解決這個問題,我們需要將我們的特征集降低到一個更有用的特征集,使用它我們可以生成有用的聚類。產(chǎn)生這樣一組特征的一種方法是進(jìn)行相關(guān)性分析。這可以通過如下繪制熱圖和3d圖來完成:
import seaborn as sns # generating correlation heatmap sns.heatmap(zoo_data.corr(), annot = True) # posting correlation heatmap to output console plt.show()

下面的代碼用于通過制作元組列表來生成相關(guān)矩陣的3d圖,其中元組包含按動物名稱順序排列的坐標(biāo)和相關(guān)值。
上述解釋的偽代碼:
# PseudoCode
tuple -> (position_in_dataframe(feature1),
position_in_dataframe(feature2),
correlation(feature1, feature2))
用于生成相關(guān)矩陣的3d圖的代碼:
from matplotlib import cm # generating correlation data df = zoo_data.corr() df.index = range(0, len(df)) df.rename(columns = dict(zip(df.columns, df.index)), inplace = True) df = df.astype(object) ''' Generating coordinates with corresponding correlation values ''' for i in range(0, len(df)): for j in range(0, len(df)): if i != j: df.iloc[i, j] = (i, j, df.iloc[i, j]) else : df.iloc[i, j] = (i, j, 0) df_list = [] # flattening dataframe values for sub_list in df.values: df_list.extend(sub_list) # converting list of tuples into trivariate dataframe plot_df = pd.DataFrame(df_list) fig = plt.figure() ax = Axes3D(fig) # plotting 3D trisurface plot ax.plot_trisurf(plot_df[0], plot_df[1], plot_df[2], cmap = cm.jet, linewidth = 0.2) plt.show()
輸出

使用熱圖和3d圖,我們可以對如何選擇用于執(zhí)行聚類分析的較小特征集進(jìn)行一些推斷。通常,具有極端相關(guān)值的特征對具有很高的解釋力,可以用于進(jìn)一步的分析。
在這種情況下,查看兩個圖,我們得到了7個特征的合理列表:[“milk”, “eggs”, “hair”, “toothed”, “feathers”, “breathes”, “aquatic”]
再次對子集特征集運行聚類分析,我們可以生成散點圖,更好地推斷如何在不同的群體中傳播不同的動物。

我們觀察到減小的總inertia為14.479670329670329,這確實比初始inertia小得多。
以上就是Python實現(xiàn)多維數(shù)據(jù)分析的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Python多維數(shù)據(jù)分析的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python Pandas中數(shù)據(jù)的合并與分組聚合
大家好,本篇文章主要講的是python Pandas中數(shù)據(jù)的合并與分組聚合,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
python如何用pymodbus庫進(jìn)行modbus tcp通信
這篇文章主要介紹了python如何用pymodbus庫進(jìn)行modbus tcp通信問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Python使用psutil庫對系統(tǒng)數(shù)據(jù)進(jìn)行采集監(jiān)控的方法
利用psutil庫可以獲取系統(tǒng)的一些信息,如cpu,內(nèi)存等使用率,從而可以查看當(dāng)前系統(tǒng)的使用情況,實時采集這些信息可以達(dá)到實時監(jiān)控系統(tǒng)的目的。本文給大家介紹Python psutil系統(tǒng)監(jiān)控的相關(guān)知識,感興趣的朋友一起看看吧2021-08-08
python連接手機自動搜集螞蟻森林能量的實現(xiàn)代碼
這篇文章主要介紹了python連接手機自動搜集螞蟻森林能量的實現(xiàn)方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02

