AHP层次分析法
具体数学内容如下:
知乎AHP详细说明
话不多说,上代码
1.依赖包
import pandas as pd
import numpy as np
from scipy.linalg import eig
np.set_printoptions(precision=6, suppress=False)
2.主体代码
class AHP():
def __init__(self):
self.RI = np.array(
[0, 0, 0.58, 0.90, 1.12, 1.24, 1.32, 1.41, 1.45, 1.49, 1.51])
self.method = 'AHP层次分析法'
def normalize(self, x0): #归一化矩阵/有时候不需要,看情况使用
return x0 / x0.sum(axis=0)
def reshapes(self, plan, n, row, col): #方案层数组reshape,用于读取数据,一般这个函数不使用
newP = plan.reshape(-1)
plans = newP.reshape((n, row, col))
return plans
def weight(self, x0): #计算准则层权重w1
eigvalues, eigvectors = eig(x0)
Lmax = eigvalues.max()
Lindex = list(eigvalues).index(Lmax)
return Lmax, eigvectors[:, Lindex] / eigvectors[:, Lindex].sum() #归一化
def CI(self, x0): #计算CI值
Lmax, weights = self.weight(x0)
Ci = (Lmax - x0.shape[0]) / (x0.shape[0] - 1)
return Ci
def judge(self, x0): #判断是否满足层次单排序及一致性检验
Ci = self.CI(x0)
CR = Ci / self.RI[x0.shape[0] - 1]
if (CR < 0.10):
return '检验通过', 'CI={}'.format(Ci) #'通过层次单排序一致性检验'
else:
return 0, 0 #'重新构造判断矩阵'
def check(self, x0, b): #判断是否满足层次总排序及一致性检验
lmax1, w1 = self.weight(x0)
CIs = np.zeros((x0.shape[0], 1))
for i in range(x0.shape[0]):
Ci = self.CI(b[i])
CIs[i] = Ci
ACIS = np.dot(np.array([w1]), CIs)
ARIS = np.dot(np.array([self.RI[:x0.shape[0]]]), np.array([w1]).T)
return '层次总排序及一致性检验值{}<0.1'.format(ACIS / ARIS)
def grade(self, w1, b): #计算得分
w1 = np.array([w1])
lmax, w2 = self.weight(b[0])
for i in range(1, b.shape[0]):
lmax, wi = self.weight(b[i])
w2 = np.vstack((w2, wi))
return np.dot(w1, w2),w1,w2
3.测试数据
#测试数据【准则层矩阵】
x0 = np.array([[1., 0.5, 4., 3., 3.], [2., 1., 7., 5., 5.],
[0.25, 0.142857, 1., 0.5, 0.333333],
[0.333333, 0.2, 2., 1., 1.], [0.333333, 0.2, 3., 1., 1.]])
########################################################################
b1 = np.array([1, 2, 5, 1 / 2, 1, 2, 1 / 5, 1 / 2, 1]).reshape((3, 3))
b2 = np.array([1, 1 / 3, 1 / 8, 3, 1, 1 / 3, 8, 3, 1]).reshape((3, 3))
b3 = np.array([1, 1, 3, 1, 1, 3, 1 / 3, 1 / 3, 1]).reshape((3, 3))
b4 = np.array([1, 3, 4, 1 / 3, 1, 1, 1 / 4, 1, 1]).reshape((3, 3))
b5 = np.array([1, 1, 1 / 4, 1, 1, 1 / 4, 4, 4, 1]).reshape((3, 3))
b = np.array([b1, b2, b3, b4, b5]) #方案层矩阵
4.测试结果(可以对照上面链接中的答案)
以上代码仍需要大量检验来检测错误,如有错误请留言!!! 谢谢
看了这么多 点个赞呗
STOP,打个广告,更多代码,聚类分析、层次分析法、熵权法、自回归、随机森林、决策树、PCA等代码,请关注