"""从非负效益分计算熵权。运行:python mmf_entropy_weight.py。""" import json # NumPy 用于列比例和熵值计算,Matplotlib 用于对照分布及平移后的权重。 import matplotlib.pyplot as plt import numpy as np def entropy_weight(values): # 行是方案,列是已经统一方向的效益分。本例使用自然对数。 if values.shape[0] < 2 or np.any(~np.isfinite(values)) or np.any(values < 0): raise ValueError("至少需要两个方案,指标需为有限的非负效益分") # totals 长度等于指标数,汇总时沿方案行求和。每列最终占比和应为 1。 totals = values.sum(axis=0) # 全零列填成均匀占比,和其他常量列一样没有区分信息。 shares = np.divide(values, totals, out=np.full_like(values, 1.0 / len(values), dtype=float), where=totals > 0) # 约定 0·log(0)=0,仅在正占比位置取对数,避免无穷和 NaN。 log_shares = np.log(shares, out=np.zeros_like(shares), where=shares > 0) # 用 log(方案数) 归一化到 [0,1];均匀占比恰有最大熵 1。 entropy = -np.sum(shares * log_shares, axis=0) / np.log(len(values)) spread = np.maximum(1 - entropy, 0.0) # 精确常量列直接归零,避免把舍入误差当成可区分差异。 spread[np.ptp(values, axis=0) == 0] = 0 # 权重需用差异系数的总和作分母;没有区分信息时停止并提示。 if spread.sum() == 0: raise ValueError("所有准则都是常量,没有可识别的熵权") return shares, entropy, spread / spread.sum() def main(): # 两处候选站点三项非负相对效益分,由题例给定,可直接比较比例。 values = np.array([[1, 2, 2], [3, 3, 2]], dtype=float) shares, entropy, weights = entropy_weight(values) shifted = values.copy() # 只改第一指标的原点,观察比例变平后,该指标的熵权如何下降。 shifted[:, 0] += 10 _, _, shifted_weights = entropy_weight(shifted) result = { "entropy": entropy.tolist(), "weights": weights.tolist(), "shifted_weights": shifted_weights.tolist(), } print("LAB_RESULT " + json.dumps(result)) fig, (distribution, comparison) = plt.subplots(1, 2, figsize=(9, 4)) criteria = np.arange(1, values.shape[1] + 1) distribution.bar(criteria, shares[0], label="Site A") distribution.bar(criteria, shares[1], bottom=shares[0], label="Site B") # 两个站点分布均匀时各占 0.5,这条线给堆叠柱提供参考。 distribution.axhline(0.5, color="0.3", linestyle="--") distribution.set(title="Indicator shares before shifting", xlabel="Indicator", ylabel="Share", xticks=criteria, ylim=(0, 1)) distribution.legend(fontsize=8) comparison.bar(criteria - 0.16, weights, width=0.32, label="Original") comparison.bar(criteria + 0.16, shifted_weights, width=0.32, label="Add 10 to column 1") comparison.set(title="Effect of shifting the origin", xlabel="Indicator", ylabel="Entropy weight", xticks=criteria, 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()