AHP | Python实现
步骤:
- 首先对指标进行相互打分
- 计算矩阵的最大特征值
- 使用最大特征值进行一致性检验
- 若第三步通过,则计算最大特征值对应的特征向量,归一化后即为指标的权重矩阵
核心代码:
import numpy as np
# 最大特征值对应的特征向量
def calculate_weight_vector(matrix):
eigvals, eigvecs = np.linalg.eig(matrix)
max_eigval_index = np.argmax(eigvals)
max_eigvec = eigvecs[:, max_eigval_index]
weight_vector = max_eigvec / np.sum(max_eigvec)
return np.real(weight_vector), np.real(eigvals[max_eigval_index])
# 一致性检验
def calculate_consistency_ratio(matrix, max_eigval):
n = matrix.shape[0]
ci = (max_eigval - n) / (n - 1)
ri_dict = {1: 0, 2: 0, 3: 0.58, 4: 0.9, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45, 10: 1.49}
ri = ri_dict.get(n, 1.49)
cr = ci / ri
return cr
comparison_matrix = np.array([]) # 填入比较的正互反矩阵
weight_vector, max_eigval = calculate_weight_vector(comparison_matrix)
consistency_ratio = calculate_consistency_ratio(comparison_matrix, max_eigval)