python实现灰色关联分析(GRA)——以红酒质量指标为例
目录
程序简介
对红酒质量指标数据进行灰色关联分析,首先进行数据标准化,然后计算关联系数矩阵和平均综合关联度
程序输入:第一列为母序列的指标矩阵
程序输出:关联度矩阵
灰色关联分析方法(GRA),是根据因素之间发展趋势的相似或相异程度,亦即“灰色关联度”,作为衡量因素间关联程度的一种方法。
程序/数据集下载
代码分析
导入模块、路径
# -*- coding: utf-8 -*- from Module.BuildModel import GraModel import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import seaborn as sns #路径目录 baseDir = ''#当前目录 staticDir = os.path.join(baseDir,'Static')#静态文件目录 resultDir = os.path.join(baseDir,'Result')#结果文件目录
读取红酒质量数据,查看内容
#接口要求第一列为母序列,即红酒质量 data = pd.read_csv(staticDir+'/winequality-red.csv',sep=';') columns = ['quality','fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar','chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density','pH', 'sulphates', 'alcohol'] data = data[columns] data.head()
quality | fixed acidity | volatile acidity | citric acid | residual sugar | chlorides | free sulfur dioxide | total sulfur dioxide | density | pH | sulphates | alcohol | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 5 | 7.4 | 0.70 | 0.00 | 1.9 | 0.076 | 11.0 | 34.0 | 0.9978 | 3.51 | 0.56 | 9.4 |
1 | 5 | 7.8 | 0.88 | 0.00 | 2.6 | 0.098 | 25.0 | 67.0 | 0.9968 | 3.20 | 0.68 | 9.8 |
2 | 5 | 7.8 | 0.76 | 0.04 | 2.3 | 0.092 | 15.0 | 54.0 | 0.9970 | 3.26 | 0.65 | 9.8 |
3 | 6 | 11.2 | 0.28 | 0.56 | 1.9 | 0.075 | 17.0 | 60.0 | 0.9980 | 3.16 | 0.58 | 9.8 |
4 | 5 | 7.4 | 0.70 | 0.00 | 1.9 | 0.076 | 11.0 | 34.0 | 0.9978 | 3.51 | 0.56 | 9.4 |
利用GraModel类建立灰色关联模型,打印结果,该类在文件夹的Module/BuildModel.py中,代码会在下文给出
#建立灰色关联模型,标准化数据 model = GraModel(data,standard=True) #模型计算结果 result = model.result #平均关联程度 meanCors = result['meanCors']['value'] print(result)
{'cors': {'value': array([[1. , 0.96198678, 0.78959431, ..., 0.75974072, 0.96920683, 0.97441242], [1. , 0.9306525 , 0.70441517, ..., 0.98976649, 0.87748443, 0.97000442], [1. , 0.9306525 , 0.75900106, ..., 0.93497649, 0.89874803, 0.97000442], ..., [1. , 0.80296849, 0.92265873, ..., 0.96266425, 0.98630178, 0.98636283], [1. , 0.91597473, 0.81988779, ..., 0.72703752, 0.85720372, 0.91902831], [1. , 0.78639314, 0.79745798, ..., 0.9909029 , 0.93720807, 0.98636283]]), 'desc': '关联系数矩阵'}, 'meanCors': {'value': array([1. , 0.87336194, 0.84594509, 0.87650184, 0.87830158, 0.87197282, 0.86374431, 0.85600195, 0.8545979 , 0.86426018, 0.89324032, 0.90374 ]), 'desc': '平均综合关联系数'}}
这是上文使用的GraModel类,该代码块可直接运行,输入矩阵,纵轴为属性名,第一列为母序列,输出为关联系数矩阵、平均综合关联系数
# -*- coding: utf-8 -*- from sklearn.preprocessing import StandardScaler import pandas as pd import numpy as np import os class GraModel(): '''灰色关联度分析模型''' def __init__(self,inputData,p=0.5,standard=True): ''' 初始化参数 inputData:输入矩阵,纵轴为属性名,第一列为母序列 p:分辨系数,范围0~1,一般取0.5,越小,关联系数间差异越大,区分能力越强 standard:是否需要标准化 ''' self.inputData = np.array(inputData) self.p = p self.standard = standard #标准化 self.standarOpt() #建模 self.buildModel() def standarOpt(self): '''标准化输入数据''' if not self.standard: return None self.scaler = StandardScaler().fit(self.inputData) self.inputData = self.scaler.transform(self.inputData) def buildModel(self): #第一列为母列,与其他列求绝对差 momCol = self.inputData[:,0].copy() sonCol = self.inputData[:,0:].copy() for col in range(sonCol.shape[1]): sonCol[:,col] = abs(sonCol[:,col]-momCol) #求两级最小差和最大差 minMin = sonCol.min() maxMax = sonCol.max() #计算关联系数矩阵 cors = (minMin + self.p*maxMax)/(sonCol+self.p*maxMax) #求平均综合关联度 meanCors = cors.mean(axis=0) self.result = {'cors':{'value':cors,'desc':'关联系数矩阵'},'meanCors':{'value':meanCors,'desc':'平均综合关联系数'}} if __name__ == "__main__": #路径目录 curDir = os.path.dirname(os.path.abspath(__file__))#当前目录 baseDir = os.path.dirname(curDir)#根目录 staticDir = os.path.join(baseDir,'Static')#静态文件目录 resultDir = os.path.join(baseDir,'Result')#结果文件目录 #读数 data = [ [1,1.1,2,2.25,3,4], [1,1.166,1.834,2,2.314,3], [1,1.125,1.075,1.375,1.625,1.75], [1,1,0.7,0.8,0.9,1.2] ] data = np.array(data).T #建模 model = GraModel(data,standard=True) print(model.result)
对平均灰色关联系数进行热力图可视化,系数可理解为所有指标与质量的关联,所以第1个值为1
#用来正常显示中文标签 plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示负号 plt.rcParams['axes.unicode_minus']=False #可视化矩阵 plt.clf() plt.figure(figsize=(8,12)) sns.heatmap(meanCors.reshape(1,-1), square=True, annot=True, cbar=False, vmax=1.0, linewidths=0.1,cmap='viridis') plt.yticks([0,],['quality']) plt.xticks(np.arange(0.5,12.5,1),columns,rotation=90) plt.title('指标关联度矩阵')