# 编写AHP方法模块
import numpy as np
class AHP():
'''
模块名称:
层次分析法
模块用途:
get_weights():计算权重
check_consisitency():检验一致性
main():主函数(可直接调用此函数获得全部结果)
'''
# 类变量(常量)
RI_DICT = {1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45, 10: 1.49}
# 输入评分矩阵(成对比较矩阵)
def __init__(self, array):
self.array = array # 成对比较矩阵(维度评分表)
self.n = array.shape[0] # 矩阵维数
# 计算权重
def get_weights(self):
sum_col = self.array.sum(axis=0) # 每列求和
divided_col = self.array/sum_col # 计算维度间相对权重
w = divided_col.sum(axis=1)/self.n # 计算各维度权重平均值
return w
# 检验一致性
def check_consisitency(self):
a, b = np.linalg.eig(self.array) # a为特征值,b为特征向量,仅提取实数部分
CI = (max(a) - self.n)/ (self.n - 1) # 非一致性指标CI
RI = self.RI_DICT[self.n] # 随机一致性指标RI
CR = CI / RI # 非一致性比率CR
if CR < 0.1:
w = self.get_weights() # 内部调用
print('评分矩阵通过一致性检验,CR值为 % .2f' %CR)
print('最大特征值:%.2f,矩阵维数:%s' %(np.real(max(a)), self.n))
print('评分矩阵的指标权重:%s' % w)
return w
else:
print('未通过一致性检验,需调整评分矩阵。CR值为 % .2f' %CR)
print('最大特征值:%.2f,矩阵维数:%s' %(np.real(max(a)), self.n))
result = ['None']
return result*self.n
# 检查输入格式
def main(self):
if type(self.array) is np.ndarray:
return self.check_consisitency() # 内部调用
else:
print('请输入numpy数组')
# 查看模块
import module_analytic
print(module_analytic.AHP.__doc__) # 显示模块内置说明
print(module_analytic.AHP.RI_DICT) # 显示类变量RI_DICT
print(module_analytic.AHP.__dict__) # 显示类包含的所有预定义属性名称、类变量、函数
print(module_analytic.AHP.__name__) # 显示类名称
print(module_analytic.AHP.__bases__) # 显示继承的父类
print(module_analytic.AHP.__module__) # 显示所属模块名称
# test_case
import numpy as np
x = np.array([[1, 1/8, 1/5, 1/2, 1/8, 1/5, 1/2],
[8,1,1/2,1,1/2,1/2,1],
[5,2,1,1,1/2,1,1],
[2,1,1,1,1/4,1/2,1],
[8,2,2,4,1,0.5,1],
[5,2,1,2,2,1,1/2],
[2,1,1,1,1,2,1]])
test_ahp = module_analytic.AHP(x) # 创建实例
test_ahp.main() #调用类的内部函数
# 读取文件
import pandas as pd
score = pd.read_excel(r'C:\Users\spark\Documents\for_practice\weights_matrix.xlsx', sheet_name='Sheet1')
array = np.array(score.ix[:,1:])
# 获取权重结果
rfm = module_analytic.AHP(array) # 创建实例rfm(即初始化)
weights = pd.DataFrame([rfm.main()], index=['weighs'], columns=score.columns.values[1:])
print(weights)