"""设备选择:由两两判断计算 AHP 权重。运行:python mmf_ahp.py。""" import json # NumPy 承担矩阵运算和特征分解;Matplotlib 用柱形对照判断修改前后的权重。 import matplotlib.pyplot as plt import numpy as np def priorities(matrix, random_index=0.58): """此实验固定三项准则,采用三阶 RI=0.58。""" if matrix.shape != (3, 3) or np.any(matrix <= 0): raise ValueError("需要一个元素均为正数的 3×3 矩阵") # * 是逐元素乘法,这里逐对检查 a_ij*a_ji=1;后面用 @ 计算矩阵乘积。 if not np.allclose(matrix * matrix.T, 1): raise ValueError("请检查对角线和成对元素的互反性") # 每一轮将上一轮权重乘以判断矩阵,再把结果归一到总和为 1。 # 正权重列向量从等权出发;差异阈值按三个分量中变化最大者判断。 weights = np.full(3, 1 / 3) for _ in range(500): product = matrix @ weights next_weights = product / product.sum() if np.max(np.abs(next_weights - weights)) < 1e-12: weights = next_weights break weights = next_weights else: raise RuntimeError("权重迭代未收敛") # 如果 Aw ≈ λw,则三个分量与各自权重的比值都接近 λ。 product = matrix @ weights largest = np.mean(product / weights) # 理论上 λ_max≥3。对接近一致的判断矩阵,将舍入造成的极小负 CI 归到 0。 ci = max(0.0, (largest - 3) / 2) # 用 NumPy 的标准特征分解独立核对幂迭代的计算。 eigenvalues, eigenvectors = np.linalg.eig(matrix) dominant = np.argmax(eigenvalues.real) reference = eigenvectors[:, dominant].real # 特征向量整体比例和符号都可变,除以分量和即可与幂迭代在同一尺度比较。 reference = reference / reference.sum() np.testing.assert_allclose(weights, reference, atol=1e-10, rtol=0) return weights, largest, ci / random_index def main(): # 准则列依次为可靠性、维护便利、外观;方案局部偏好已有评分依据。 matrix = np.array([[1, 2, 6], [1 / 2, 1, 3], [1 / 6, 1 / 3, 1]]) local_scores = np.array([[0.8, 0.6, 0.3], [0.2, 0.4, 0.7]]) weights, largest, cr = priorities(matrix) # 2×3 的局部评分矩阵每行一个方案,乘三个准则权重得到长度为 2 的综合分。 scores = local_scores @ weights # 改动一对元素以保持互反,与原来的传递关系形成冲突。 changed = matrix.copy() changed[0, 2], changed[2, 0] = 2, 1 / 2 changed_weights, _, changed_cr = priorities(changed) result = { "weights": weights.tolist(), "lambda_max": float(largest), "cr": float(cr), "scores": scores.tolist(), "changed_weights": changed_weights.tolist(), "changed_cr": float(changed_cr), } print("LAB_RESULT " + json.dumps(result)) # 左图并排放原矩阵和修改版的权重;右图的综合分来自原权重。 fig, (weight_plot, score_plot) = plt.subplots(1, 2, figsize=(9, 4)) criteria = np.arange(3) weight_plot.bar(criteria - 0.16, weights, width=0.32, label="Original") weight_plot.bar(criteria + 0.16, changed_weights, width=0.32, label="Edited pair") weight_plot.set_xticks(criteria, ["Reliability", "Maintenance", "Appearance"]) weight_plot.set(title="Priority weights after a judgment edit", ylabel="Weight") weight_plot.legend() score_plot.bar(["A", "B"], scores) score_plot.set(title="Scores with the original weights", ylabel="Weighted score", ylim=(0, 1)) fig.tight_layout() if plt.get_backend().lower() == "agg": fig.canvas.draw() else: plt.show() if __name__ == "__main__": main()