"""两项效益指标的 TOPSIS。运行:python mmf_topsis.py。""" import json # NumPy 把指标列转成可比较的加权坐标,Matplotlib 展示理想点几何与排序变化。 import matplotlib.pyplot as plt import numpy as np def topsis(values, weights): # 每一列是一个效益指标。向量归一化用列范数,而不是逐行除。 # values 的形状为 (方案数, 指标数),长度向量每个指标一个元素。 lengths = np.sqrt(np.sum(values**2, axis=0)) scaled = values / np.where(lengths == 0, 1, lengths) np.testing.assert_allclose(lengths, np.linalg.norm(values, axis=0)) # 一维权重沿每一行广播,给该行的各指标分别缩放;两列均为效益型。 weighted = scaled * weights ideal = np.max(weighted, axis=0) anti_ideal = np.min(weighted, axis=0) # 加权矩阵的每一行是一点,分别计算它到正负理想解的欧氏距离。 d_plus = np.linalg.norm(weighted - ideal, axis=1) d_minus = np.linalg.norm(weighted - anti_ideal, axis=1) # 两理想点完全重合时该方案的两个距离都为 0,约定贴近度 0.5。 total = d_plus + d_minus score = np.divide(d_minus, total, out=np.full(len(values), 0.5), where=total > 0) return score, weighted, ideal, anti_ideal, d_plus, d_minus def main(): # 行为四个虚构的方案,列分别为服务能力、响应便捷度,越大越好。 values = np.array([[2, 6], [3, 5], [4, 4], [5, 3]], dtype=float) weights = np.array([0.5, 0.5]) changed_weights = np.array([0.2, 0.8]) score, weighted, ideal, anti_ideal, d_plus, d_minus = topsis(values, weights) # *_ 收集本次不需要的中间量;这次只为对比新的贴近度和名次。 changed_score, *_ = topsis(values, changed_weights) # 返回 1 开始的方案编号,与表格及 MATLAB 的编号相同。 result = { "scores": score.tolist(), "order": (np.argsort(-score, kind="stable") + 1).tolist(), "d_plus": d_plus.tolist(), "d_minus": d_minus.tolist(), "changed_scores": changed_score.tolist(), "changed_order": (np.argsort(-changed_score, kind="stable") + 1).tolist(), } print("LAB_RESULT " + json.dumps(result)) fig, (geometry, comparison) = plt.subplots(1, 2, figsize=(9, 4)) geometry.scatter(*weighted.T, label="Alternatives") geometry.scatter(*ideal, marker="*", s=100, label="Positive ideal") geometry.scatter(*anti_ideal, marker="x", s=55, label="Negative ideal") for index, point in enumerate(weighted, start=1): geometry.annotate(str(index), point, xytext=(4, 4), textcoords="offset points") for reference in (ideal, anti_ideal): segment = np.vstack([weighted[1], reference]) geometry.plot(*segment.T, "--", color="0.45") geometry.set(xlabel="Weighted criterion 1", ylabel="Weighted criterion 2", title="Distances from alternative 2") # 两轴使用相同比例,虚线段的长短才可按欧氏距离直观比较。 geometry.set_aspect("equal") geometry.legend(fontsize=8) # 每个方案的两条相邻柱对应两组权重,纵轴固定为 0–1 便于比较。 ids = np.arange(1, 5) comparison.bar(ids - 0.16, score, width=0.32, label="w = (0.5, 0.5)") comparison.bar(ids + 0.16, changed_score, width=0.32, label="w = (0.2, 0.8)") comparison.set(xlabel="Alternative", ylabel="Closeness", xticks=ids, ylim=(0, 1)) comparison.legend(fontsize=8) fig.tight_layout() if plt.get_backend().lower() == "agg": fig.canvas.draw() else: plt.show() if __name__ == "__main__": main()