Python实现灰色关联分析与结果可视化的详细代码

2022-07-16,,,,

之前在比赛的时候需要用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实现灰色关联

到此这篇关于python实现灰色关联分析与结果可视化的文章就介绍到这了,更多相关python灰色关联分析内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Python实现灰色关联分析与结果可视化的详细代码.doc》

下载本文的Word格式文档,以方便收藏与打印。