日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python實現灰色關聯分析與結果可視化的詳細代碼_python

作者:FontTian的專欄 ? 更新時間: 2022-05-29 編程語言

之前在比賽的時候需要用Python實現灰色關聯分析,從網上搜了下只有實現兩個列之間的,于是我把它改寫成了直接想Pandas中的計算工具直接計算person系數那樣的形式,可以對整個矩陣進行運算,并給出了可視化效果,效果請見實現

灰色關聯分析法

對于兩個系統之間的因素,其隨時間或不同對象而變化的關聯性大小的量度,稱為關聯度。在系統發展過程中,若兩個因素變化的趨勢具有一致性,即同步變化程度較高,即可謂二者關聯程度較高;反之,則較低。因此,灰色關聯分析方法,是根據因素之間發展趨勢的相似或相異程度,亦即“灰色關聯度”,作為衡量因素間關聯程度的一種方法。

簡介

灰色系統理論提出了對各子系統進行灰色關聯度分析的概念,意圖透過一定的方法,去尋求系統中各子系統(或因素)之間的數值關系。因此,灰色關聯度分析對于一個系統發展變化態勢提供了量化的度量,非常適合動態歷程分析。

計算步驟

  • 確實參考數列與比較數列
  • 對參考數列與比較數列進行無量綱化處理
  • 計算關聯系數,求關聯度

此處我給出的是第三步的實現方式,無量綱化請自己處理.數據使用UCI的紅酒質量數據集.

代碼實現

下載數據

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# 定義下載數據的函數
def ReadAndSaveDataByPandas(target_url = None,file_save_path = None ,save=False):
    if target_url !=None:
        target_url = ("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv")   
    if file_save_path != None:
        file_save_path = "/home/fonttian/Data/UCI/Glass/glass.csv"
    wine = pd.read_csv(target_url, header=0, sep=";")
    if save == True:
        wine.to_csv(file_save_path, index=False)
    return wine
# 從硬盤讀取數據進入內存
wine = pd.read_csv("/home/font/Data/UCI/WINE/wine.csv")
wine.head()

實現灰色關聯分析

import pandas as pd
from numpy import *
def GRA_ONE(DataFrame,m=0):
    gray= DataFrame
    #讀取為df格式
    gray=(gray - gray.min()) / (gray.max() - gray.min())
    #標準化
    std=gray.iloc[:,m]#為標準要素
    ce=gray.iloc[:,0:]#為比較要素
    n=ce.shape[0]
    m=ce.shape[1]#計算行列

    #與標準要素比較,相減
    a=zeros([m,n])
    for i in range(m):
        for j in range(n):
            a[i,j]=abs(ce.iloc[j,i]-std[j])
    #取出矩陣中最大值與最小值
    c=amax(a)
    d=amin(a)
    #計算值
    result=zeros([m,n])
            result[i,j]=(d+0.5*c)/(a[i,j]+0.5*c)
    #求均值,得到灰色關聯值
    result2=zeros(m)
            result2[i]=mean(result[i,:])
    RT=pd.DataFrame(result2)
    return RT
def GRA(DataFrame):
    list_columns = [str(s) for s in range(len(DataFrame.columns)) if s not in [None]]
    df_local = pd.DataFrame(columns=list_columns)
    for i in range(len(DataFrame.columns)):
        df_local.iloc[:,i] = GRA_ONE(DataFrame,m=i)[0]
    return df_local
data_wine_gra = GRA(wine)
# data_wine_gra.to_csv(path+"GRA.csv") 存儲結果到硬盤
data_wine_gra
Empty DataFrame
Columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Index: []

結果可視化

# 灰色關聯結果矩陣可視化
import seaborn as sns
%matplotlib inline
def ShowGRAHeatMap(DataFrame):
    import matplotlib.pyplot as plt
    import seaborn as sns
    %matplotlib inline
    colormap = plt.cm.RdBu
    plt.figure(figsize=(14,12))
    plt.title('Pearson Correlation of Features', y=1.05, size=15)
    sns.heatmap(DataFrame.astype(float),linewidths=0.1,vmax=1.0, square=True, cmap=colormap, linecolor='white', annot=True)
    plt.show()
ShowGRAHeatMap(data_wine_gra)

參考文章

  • 百度百科 灰色關聯分析法
  • 簡書 Python實現灰色關聯

原文鏈接:https://www.cnblogs.com/fonttian/p/9162716.html

欄目分類
最近更新