Skip to content

XiaoMaColtAI/math-modeling-skill

math-modeling

Verified

当用户要求数学建模、建模竞赛、建模分析、代码求解、结果可视化或生成数学建模论文时使用。支持完整三阶段流程、单独执行任一角色,以及在关键节点使用独立 Subagent 进行阶段内质检;默认只启用质检 Subagent,用户可明确选择额外协作。

assets/03-评价类算法说明.md

View on GitHub
# 评价类算法说明文档

## 概述

评价类算法是数学建模中的重要算法类型,用于对多指标、多方案进行综合评价和排序。评价问题广泛存在于方案选优、绩效考核、质量评估、风险评价等领域。

---

## 1. 层次分析法 (Analytic Hierarchy Process, AHP)

### 算法介绍

层次分析法是由美国运筹学家Saaty提出的一种定性与定量相结合的多准则决策方法。通过构建判断矩阵,计算权重,进行一致性检验。

#### 1.1 构建判断矩阵

对n个指标两两比较,得到判断矩阵$A = (a_{ij})_{n \times n}$,其中$a_{ij}$表示指标$i$相对于指标$j$的重要程度。

**Saaty标度**:

| 标度 | 含义 |
|-----|------|
| 1 | 两个因素同等重要 |
| 3 | 前者比后者稍微重要 |
| 5 | 前者比后者明显重要 |
| 7 | 前者比后者强烈重要 |
| 9 | 前者比后者极端重要 |
| 2,4,6,8 | 上述相邻判断的中间值 |
| 倒数 | 后者比前者的重要程度 |

判断矩阵满足:$a_{ij} > 0$, $a_{ji} = 1/a_{ij}$, $a_{ii} = 1$

#### 1.2 权重计算

**和积法**:

1. 将判断矩阵按列归一化:$\bar{a}_{ij} = a_{ij} / \sum_{k=1}^{n} a_{kj}$

2. 按行求和:$\bar{w}_i = \sum_{j=1}^{n} \bar{a}_{ij}$

3. 归一化得到权重:$w_i = \bar{w}_i / \sum_{k=1}^{n} \bar{w}_k$

**特征根法**:

求解特征值问题:$Aw = \lambda_{\max} w$

权重向量$w$对应最大特征值$\lambda_{\max}$的特征向量。

#### 1.3 一致性检验

**计算一致性指标CI**:
$$
CI = \frac{\lambda_{\max} - n}{n - 1}
$$

**计算一致性比例CR**:
$$
CR = \frac{CI}{RI}
$$

其中RI是随机一致性指标:

| n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|----|
| RI | 0 | 0 | 0.58 | 0.90 | 1.12 | 1.24 | 1.32 | 1.41 | 1.45 | 1.49 |

**判定标准**:当$CR < 0.1$时,认为判断矩阵具有满意的一致性。

#### 1.4 综合评价

**方案总排序**:
$$
S_i = \sum_{j=1}^{n} w_j \cdot r_{ij}
$$

其中$w_j$是指标权重,$r_{ij}$是方案$i$在指标$j$上的得分(归一化后)。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 方案选优 | 最佳方案选择 | 多准则决策 |
| 绩效评价 | 员工/部门绩效考核 | 多指标评估 |
| 风险评估 | 项目风险评价 | 多因素风险 |
| 质量评估 | 产品/服务质量评价 | 多维度质量 |
| 供应商选择 | 供应商评价选择 | 多属性决策 |
| 城市发展评价 | 城市综合发展水平 | 多指标评价 |

### 可视化图表类型

- **层次结构图**:评价指标的层次结构
- **权重分布图**:各指标权重对比
- **方案得分雷达图**:各方案得分对比
- **一致性分析图**:CI/CR值分析
- **敏感性分析图**:权重变化对排序的影响

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| The Analytic Hierarchy Process | Thomas L. Saaty | 1980 | McGraw-Hill |
| Decision Making for Leaders | Saaty & Vargas | 2001 | RWS Publications |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体 - 多字体备选防止渲染问题
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans', 'Arial Unicode MS', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False

class AHPAnalyzer:
    """
    层次分析法(AHP)分析类
    """
    
    # 随机一致性指标RI
    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}
    
    @staticmethod
    def calculate_weights_eigenvalue(matrix):
        """
        特征根法计算权重
        :param matrix: 判断矩阵
        :return: 权重向量, 最大特征值, CI, CR, 一致性检验结果
        """
        n = len(matrix)
        
        # 计算特征值和特征向量
        eigenvalues, eigenvectors = np.linalg.eig(matrix)
        
        # 找最大特征值及其对应的特征向量
        max_idx = np.argmax(eigenvalues)
        lambda_max = eigenvalues[max_idx].real
        weight_vector = eigenvectors[:, max_idx].real
        
        # 归一化权重
        weight_vector = weight_vector / weight_vector.sum()
        
        # 一致性检验
        CI = (lambda_max - n) / (n - 1)
        RI = AHPAnalyzer.RI_DICT.get(n, 1.49)
        CR = CI / RI if RI != 0 else 0
        
        # 一致性检验结果
        is_consistent = CR < 0.1
        
        return weight_vector, lambda_max, CI, CR, is_consistent
    
    @staticmethod
    def calculate_weights_geometric(matrix):
        """
        几何平均法计算权重
        :param matrix: 判断矩阵
        :return: 权重向量
        """
        n = len(matrix)
        
        # 计算每行的几何平均数
        geometric_means = np.power(np.prod(matrix, axis=1), 1/n)
        
        # 归一化
        weights = geometric_means / geometric_means.sum()
        
        return weights
    
    @staticmethod
    def calculate_weights_sum(matrix):
        """
        和积法计算权重
        :param matrix: 判断矩阵
        :return: 权重向量
        """
        n = len(matrix)
        
        # 列归一化
        col_sum = matrix.sum(axis=0)
        normalized = matrix / col_sum
        
        # 行求和并归一化
        row_sum = normalized.sum(axis=1)
        weights = row_sum / row_sum.sum()
        
        return weights
    
    @staticmethod
    def create_comparison_matrix(criteria_names, comparisons):
        """
        根据两两比较创建判断矩阵
        :param criteria_names: 指标名称列表
        :param comparisons: 字典 {(i,j): value} 表示指标i相对于指标j的重要性
        :return: 判断矩阵
        """
        n = len(criteria_names)
        matrix = np.ones((n, n))
        
        for (i, j), value in comparisons.items():
            matrix[i, j] = value
            matrix[j, i] = 1 / value
        
        return matrix
    
    @staticmethod
    def comprehensive_evaluation(weights, scores):
        """
        AHP综合评价
        :param weights: 指标权重向量
        :param scores: 方案得分矩阵 (方案数 × 指标数)
        :return: 各方案综合得分
        """
        scores = np.array(scores)
        weights = np.array(weights)
        
        # 归一化得分矩阵(列归一化)
        col_sums = scores.sum(axis=0)
        col_sums[col_sums == 0] = 1  # 避免除零
        normalized_scores = scores / col_sums
        
        # 计算综合得分
        total_scores = normalized_scores @ weights
        
        return total_scores

def visualize_ahp_results(matrix, weights, lambda_max, CI, CR, is_consistent, criteria_names=None):
    """可视化AHP分析结果"""
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 2, height_ratios=[1, 1, 1])
    
    n = len(matrix)
    if criteria_names is None:
        criteria_names = [f'指标{i+1}' for i in range(n)]
    
    # 图1:判断矩阵热力图
    ax1 = fig.add_subplot(gs[0, 0])
    im1 = ax1.imshow(matrix, cmap='YlOrRd', aspect='auto')
    
    # 标注数值
    for i in range(n):
        for j in range(n):
            text = ax1.text(j, i, f'{matrix[i, j]:.2f}',
                          ha="center", va="center", color="black", fontsize=9)
    
    ax1.set_xticks(range(n))
    ax1.set_yticks(range(n))
    ax1.set_xticklabels(criteria_names, rotation=45, ha='right')
    ax1.set_yticklabels(criteria_names)
    ax1.set_title('AHP判断矩阵', fontsize=14)
    plt.colorbar(im1, ax=ax1)
    
    # 图2:权重分布
    ax2 = fig.add_subplot(gs[0, 1])
    colors = plt.cm.viridis(np.linspace(0, 1, n))
    bars = ax2.barh(criteria_names, weights, color=colors, edgecolor='black')
    
    # 添加数值标签
    for bar, weight in zip(bars, weights):
        width = bar.get_width()
        ax2.text(width, bar.get_y() + bar.get_height()/2, 
                f'{weight:.4f}', ha='left', va='center', fontsize=10)
    
    ax2.set_xlabel('权重', fontsize=12)
    ax2.set_title('指标权重分布', fontsize=14)
# 图3:一致性检验
    ax3 = fig.add_subplot(gs[1, :])
    
    # 一致性指标对比
    metrics = ['λ_max', 'CI', 'CR', '一致性阈值']
    values = [lambda_max, CI, CR, 0.1]
    colors_bar = ['blue', 'green', 'red' if not is_consistent else 'green', 'orange']
    
    bars = ax3.bar(metrics, values, color=colors_bar, edgecolor='black', alpha=0.7)
    
    # 添加数值标签
    for bar, value in zip(bars, values):
        height = bar.get_height()
        ax3.text(bar.get_x() + bar.get_width()/2., height,
                f'{value:.4f}', ha='center', va='bottom', fontsize=11)
    
    # 添加一致性判定
    status_text = '通过' if is_consistent else '未通过'
    status_color = 'green' if is_consistent else 'red'
    ax3.text(0.95, 0.95, f'一致性检验: {status_text}', 
            transform=ax3.transAxes, ha='right', va='top',
            bbox=dict(boxstyle='round', facecolor=status_color, alpha=0.3),
            fontsize=12, fontweight='bold')
    
    ax3.set_ylabel('数值', fontsize=12)
    ax3.set_title('一致性检验指标', fontsize=14)
# 图4:权重饼图
    ax4 = fig.add_subplot(gs[2, 0])
    
    # 只显示大于5%的权重
    threshold = 0.05
    significant_indices = weights > threshold
    
    if significant_indices.sum() < n:
        # 有较小的权重,合并为"其他"
        significant_weights = weights[significant_indices]
        other_weight = weights[~significant_indices].sum()
        
        plot_weights = list(significant_weights) + [other_weight]
        plot_labels = [criteria_names[i] for i in range(n) if significant_indices[i]] + ['其他']
    else:
        plot_weights = weights
        plot_labels = criteria_names
    
    wedges, texts, autotexts = ax4.pie(plot_weights, labels=plot_labels, autopct='%1.1f%%',
                                        startangle=90, colors=plt.cm.Set3.colors)
    ax4.set_title('权重占比分布', fontsize=14)
    
    # 图5:判断矩阵一致性可视化
    ax5 = fig.add_subplot(gs[2, 1])
    
    # 计算一致性矩阵 (A * w) / (λ_max * w)
    consistency_vector = (matrix @ weights) / (lambda_max * weights)
    
    ax5.bar(criteria_names, consistency_vector, color='skyblue', edgecolor='black', alpha=0.7)
    ax5.axhline(y=1, color='r', linestyle='--', linewidth=2, label='理想值=1')
    ax5.set_ylabel('一致性比值', fontsize=12)
    ax5.set_title('判断矩阵一致性检验 (Aw/λw)', fontsize=14)
    ax5.legend()
# 旋转x轴标签
    plt.setp(ax5.xaxis.get_majorticklabels(), rotation=45, ha='right')
    
    plt.tight_layout()
    plt.savefig('ahp_analysis_results.png', dpi=150, bbox_inches='tight')
    plt.show()
    
    print("\n图表已保存为 'ahp_analysis_results.png'")

# 运行示例
if __name__ == "__main__":
    print("=" * 60)
    print("层次分析法(AHP)示例")
    print("=" * 60)
    
    # 示例:选择最佳旅游目的地的AHP分析
    criteria = ['景色', '费用', '居住', '饮食', '交通']
    
    # 构建判断矩阵(根据Saaty标度)
    # 景色比费用稍微重要(3),比居住明显重要(5),等等
    comparisons = {
        (0, 1): 3,   # 景色 vs 费用
        (0, 2): 5,   # 景色 vs 居住
        (0, 3): 4,   # 景色 vs 饮食
        (0, 4): 2,   # 景色 vs 交通
        (1, 2): 1/3, # 费用 vs 居住
        (1, 3): 1/2, # 费用 vs 饮食
        (1, 4): 1/2, # 费用 vs 交通
        (2, 3): 2,   # 居住 vs 饮食
        (2, 4): 3,   # 居住 vs 交通
        (3, 4): 2,   # 饮食 vs 交通
    }
    
    matrix = AHPAnalyzer.create_comparison_matrix(criteria, comparisons)
    
    print("\n判断矩阵:")
    print(matrix)
    
    # 计算权重(特征根法)
    weights, lambda_max, CI, CR, is_consistent = AHPAnalyzer.calculate_weights_eigenvalue(matrix)
    
    print(f"\n最大特征值 λ_max = {lambda_max:.4f}")
    print(f"一致性指标 CI = {CI:.4f}")
    print(f"一致性比例 CR = {CR:.4f}")
    print(f"一致性检验: {'通过' if is_consistent else '未通过'} (CR < 0.1)")
    
    print("\n指标权重:")
    for i, (criterion, weight) in enumerate(zip(criteria, weights)):
        print(f"  {criterion}: {weight:.4f}")
    
    # 方案评价
    print("\n" + "=" * 60)
    print("方案综合评价")
    print("=" * 60)
    
    # 三个旅游目的地的得分(5分制)
    destinations = ['目的地A', '目的地B', '目的地C']
    scores = np.array([
        [4, 3, 5, 4, 3],  # 目的地A
        [5, 2, 4, 3, 4],  # 目的地B
        [3, 5, 3, 5, 2],  # 目的地C
    ])
    
    print("\n方案得分矩阵:")
    print("        景色  费用  居住  饮食  交通")
    for dest, score in zip(destinations, scores):
        print(f"{dest}: {score}")
    
    # 计算综合得分
    total_scores = AHPAnalyzer.comprehensive_evaluation(weights, scores)
    
    print("\n综合得分:")
    for dest, score in zip(destinations, total_scores):
        print(f"  {dest}: {score:.4f}")
    
    # 排序
    ranking = np.argsort(-total_scores)
    print("\n推荐排序:")
    for i, idx in enumerate(ranking):
        print(f"  第{i+1}名: {destinations[idx]} (得分: {total_scores[idx]:.4f})")
    
    # 可视化
    visualize_ahp_results(matrix, weights, lambda_max, CI, CR, is_consistent, criteria)
```

---

## 2. 模糊层次分析法 (Fuzzy-AHP)

### 算法介绍

模糊层次分析法将模糊数学理论引入AHP,用模糊数代替精确数进行判断,更好地处理决策中的不确定性和模糊性。

#### 2.1 模糊数与判断矩阵

**三角模糊数**:$\tilde{M} = (l, m, u)$

其中$l \leq m \leq u$,$m$为最可能值,$l$和$u$为下界和上界。

**模糊判断矩阵**:$\tilde{A} = (\tilde{a}_{ij})_{n \times n}$

#### 2.2 模糊权重计算

**模糊权重**:
$$
\tilde{w}_i = \frac{\sum_{j=1}^{n} \tilde{a}_{ij}}{\sum_{i=1}^{n}\sum_{j=1}^{n} \tilde{a}_{ij}}
$$

**去模糊化**(重心法):
$$
w_i = \frac{l_i + m_i + u_i}{3}
$$

#### 2.3 模糊综合评价

$$
\tilde{S} = \tilde{W} \circ \tilde{R}
$$

其中$\tilde{W}$是模糊权重向量,$\tilde{R}$是模糊评价矩阵,$\circ$是模糊合成算子。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 不确定决策 | 方案选择 | 判断模糊 |
| 风险评估 | 项目风险评价 | 风险不确定 |
| 质量评价 | 服务质量评价 | 主观性强 |
| 供应商选择 | 供应商评价 | 信息不完整 |
| 人才评价 | 人才选拔评价 | 定性指标多 |

### 可视化图表类型

- **模糊数分布图**:模糊数的隶属函数
- **权重区间图**:权重的上下界
- **得分区间图**:方案得分的区间
- **灵敏度分析图**:模糊程度对结果的影响

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| The Analytic Hierarchy Process with Fuzzy Ratings | Van Laarhoven & Pedrycz | 1983 | Fuzzy Sets and Systems |
| Fuzzy Multiple Attribute Decision Making | Chen & Hwang | 1992 | Springer |

### 代码实现要点

```python
import numpy as np

class FuzzyNumber:
    """三角模糊数"""
    def __init__(self, l, m, u):
        self.l = l
        self.m = m
        self.u = u

    def __add__(self, other):
        return FuzzyNumber(self.l + other.l, self.m + other.m, self.u + other.u)

    def __mul__(self, scalar):
        return FuzzyNumber(self.l * scalar, self.m * scalar, self.u * scalar)

    def defuzzify(self):
        """去模糊化(重心法)"""
        return (self.l + self.m + self.u) / 3

def fuzzy_ahp_weight(fuzzy_matrix):
    """
    模糊AHP权重计算
    :param fuzzy_matrix: 模糊判断矩阵(FuzzyNumber对象)
    :return: 去模糊化后的权重向量
    """
    n = len(fuzzy_matrix)
    fuzzy_weights = []

    for i in range(n):
        # 计算模糊权重
        sum_l = sum(fuzzy_matrix[i][j].l for j in range(n))
        sum_m = sum(fuzzy_matrix[i][j].m for j in range(n))
        sum_u = sum(fuzzy_matrix[i][j].u for j in range(n))

        total_l = sum(fuzzy_matrix[i][j].l for i in range(n) for j in range(n))
        total_m = sum(fuzzy_matrix[i][j].m for i in range(n) for j in range(n))
        total_u = sum(fuzzy_matrix[i][j].u for i in range(n) for j in range(n))

        fuzzy_weights.append(FuzzyNumber(
            sum_l / total_u,
            sum_m / total_m,
            sum_u / total_l
        ))

    # 去模糊化
    weights = np.array([fw.defuzzify() for fw in fuzzy_weights])
    weights = weights / weights.sum()

    return weights
```

---

## 3. 熵权法 (Entropy Weight Method, EWM)

### 算法介绍

熵权法是一种客观赋权方法,根据指标数据的离散程度确定权重。信息熵越小,指标离散程度越大,提供的信息量越大,权重越大。

#### 3.1 数据标准化

**正向指标**(越大越好):
$$
r_{ij} = \frac{x_{ij} - \min_j x_{ij}}{\max_j x_{ij} - \min_j x_{ij}}
$$

**负向指标**(越小越好):
$$
r_{ij} = \frac{\max_j x_{ij} - x_{ij}}{\max_j x_{ij} - \min_j x_{ij}}
$$

#### 3.2 计算比重

$$
p_{ij} = \frac{r_{ij}}{\sum_{i=1}^{m} r_{ij}}
$$

为避免$\ln 0$,通常进行坐标平移:$p_{ij} = \frac{1 + r_{ij}}{\sum_{i=1}^{m} (1 + r_{ij})}$

#### 3.3 计算信息熵

$$
e_j = -\frac{1}{\ln m} \sum_{i=1}^{m} p_{ij} \ln p_{ij}
$$

#### 3.4 计算权重

**信息效用值**:$d_j = 1 - e_j$

**权重**:$w_j = \frac{d_j}{\sum_{k=1}^{n} d_k}$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 综合评价 | 多指标综合评价 | 数据驱动 |
| 方案选优 | 最佳方案选择 | 客观赋权 |
| 绩效评估 | 地区/部门绩效 | 数据充分 |
| 风险评估 | 项目风险评价 | 基于数据 |
| 质量评价 | 产品质量评价 | 数据完整 |

### 可视化图表类型

- **权重分布图**:各指标权重对比
- **信息熵对比图**:各指标信息熵
- **信息效用值图**:各指标信息效用
- **得分排名图**:方案得分排名
- **敏感性分析图**:数据变化对权重的影响

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Information Theory and Entropy | Shannon | 1948 | Bell System Technical Journal |
| Multi-attribute decision making | Zou et al. | 2006 | Systems Engineering and Electronics |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体 - 多字体备选防止渲染问题
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans', 'Arial Unicode MS', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False

class EntropyWeightMethod:
    """
    熵权法评价类
    """
    
    @staticmethod
    def normalize_data(data, directions=None):
        """
        数据标准化
        :param data: 数据矩阵 (样本×指标)
        :param directions: 指标方向,1为正向,-1为负向
        :return: 标准化后的数据
        """
        data = np.array(data, dtype=float)
        m, n = data.shape
        
        if directions is None:
            directions = np.ones(n)
        else:
            directions = np.array(directions)
        
        normalized = np.zeros_like(data, dtype=float)
        
        for j in range(n):
            min_val = data[:, j].min()
            max_val = data[:, j].max()
            range_val = max_val - min_val
            
            if range_val == 0:
                normalized[:, j] = 1
            else:
                if directions[j] == 1:  # 正向指标
                    normalized[:, j] = (data[:, j] - min_val) / range_val
                else:  # 负向指标
                    normalized[:, j] = (max_val - data[:, j]) / range_val
        
        return normalized
    
    @staticmethod
    def calculate_weights(data, directions=None):
        """
        熵权法计算权重
        :param data: 数据矩阵 (样本×指标)
        :param directions: 指标方向列表
        :return: 权重向量, 信息熵, 信息效用值, 标准化数据
        """
        data = np.array(data, dtype=float)
        m, n = data.shape
        
        # 标准化
        normalized = EntropyWeightMethod.normalize_data(data, directions)
        
        # 坐标平移(避免ln(0))
        shifted = normalized + 0.0001
        
        # 计算比重
        p = shifted / shifted.sum(axis=0)
        
        # 计算信息熵
        e = np.zeros(n)
        for j in range(n):
            # 处理p为0的情况
            p_j = p[:, j]
            log_p = np.log(p_j)
            log_p[p_j == 0] = 0  # 避免log(0)
            e[j] = -1 / np.log(m) * np.sum(p_j * log_p)
        
        # 计算信息效用值和权重
        d = 1 - e
        weights = d / d.sum()
        
        return weights, e, d, normalized
    
    @staticmethod
    def evaluate(data, directions=None):
        """
        熵权法综合评价
        :param data: 数据矩阵 (样本×指标)
        :param directions: 指标方向
        :return: 各样本综合得分, 权重, 信息熵, 信息效用值
        """
        weights, e, d, normalized = EntropyWeightMethod.calculate_weights(data, directions)
        
        # 计算综合得分
        scores = normalized @ weights
        
        return scores, weights, e, d, normalized

def visualize_entropy_results(data, weights, entropy, utility, normalized, 
                              sample_names=None, indicator_names=None, directions=None):
    """可视化熵权法分析结果"""
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 2, height_ratios=[1, 1, 1])
    
    m, n = data.shape
    if sample_names is None:
        sample_names = [f'样本{i+1}' for i in range(m)]
    if indicator_names is None:
        indicator_names = [f'指标{i+1}' for i in range(n)]
    
    # 图1:原始数据热力图
    ax1 = fig.add_subplot(gs[0, 0])
    im1 = ax1.imshow(data, cmap='YlOrRd', aspect='auto')
    
    for i in range(m):
        for j in range(n):
            text = ax1.text(j, i, f'{data[i, j]:.1f}',
                          ha="center", va="center", color="black", fontsize=9)
    
    ax1.set_xticks(range(n))
    ax1.set_yticks(range(m))
    ax1.set_xticklabels(indicator_names, rotation=45, ha='right')
    ax1.set_yticklabels(sample_names)
    ax1.set_title('原始数据矩阵', fontsize=14)
    plt.colorbar(im1, ax=ax1)
    
    # 图2:标准化数据热力图
    ax2 = fig.add_subplot(gs[0, 1])
    im2 = ax2.imshow(normalized, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
    
    for i in range(m):
        for j in range(n):
            text = ax2.text(j, i, f'{normalized[i, j]:.2f}',
                          ha="center", va="center", color="black", fontsize=9)
    
    ax2.set_xticks(range(n))
    ax2.set_yticks(range(m))
    ax2.set_xticklabels(indicator_names, rotation=45, ha='right')
    ax2.set_yticklabels(sample_names)
    ax2.set_title('标准化数据矩阵', fontsize=14)
    plt.colorbar(im2, ax=ax2)
    
    # 图3:信息熵和信息效用值
    ax3 = fig.add_subplot(gs[1, 0])
    
    x = np.arange(n)
    width = 0.35
    
    bars1 = ax3.bar(x - width/2, entropy, width, label='信息熵', color='lightcoral', edgecolor='black')
    bars2 = ax3.bar(x + width/2, utility, width, label='信息效用值', color='lightblue', edgecolor='black')
    
    ax3.set_xlabel('指标', fontsize=12)
    ax3.set_ylabel('数值', fontsize=12)
    ax3.set_title('信息熵与信息效用值对比', fontsize=14)
    ax3.set_xticks(x)
    ax3.set_xticklabels(indicator_names, rotation=45, ha='right')
    ax3.legend()
# 图4:权重分布
    ax4 = fig.add_subplot(gs[1, 1])
    
    colors = plt.cm.viridis(np.linspace(0, 1, n))
    bars = ax4.bar(indicator_names, weights, color=colors, edgecolor='black')
    
    # 添加数值标签
    for bar, weight in zip(bars, weights):
        height = bar.get_height()
        ax4.text(bar.get_x() + bar.get_width()/2., height,
                f'{weight:.4f}', ha='center', va='bottom', fontsize=10)
    
    ax4.set_ylabel('权重', fontsize=12)
    ax4.set_title('熵权法权重分布', fontsize=14)
    plt.setp(ax4.xaxis.get_majorticklabels(), rotation=45, ha='right')
    
    # 图5:综合得分排名
    ax5 = fig.add_subplot(gs[2, :])
    
    scores = normalized @ weights
    sorted_indices = np.argsort(-scores)
    sorted_scores = scores[sorted_indices]
    sorted_names = [sample_names[i] for i in sorted_indices]
    
    colors_score = plt.cm.RdYlGn(sorted_scores / sorted_scores.max())
    bars = ax5.barh(sorted_names[::-1], sorted_scores[::-1], color=colors_score[::-1], edgecolor='black')
    
    # 添加数值标签
    for bar, score in zip(bars, sorted_scores[::-1]):
        width = bar.get_width()
        ax5.text(width, bar.get_y() + bar.get_height()/2, 
                f'{score:.4f}', ha='left', va='center', fontsize=10)
    
    ax5.set_xlabel('综合得分', fontsize=12)
    ax5.set_title('样本综合得分排名', fontsize=14)
    plt.tight_layout()
    plt.savefig('entropy_weight_results.png', dpi=150, bbox_inches='tight')
    plt.show()
    
    print("\n图表已保存为 'entropy_weight_results.png'")

# 运行示例
if __name__ == "__main__":
    print("=" * 60)
    print("熵权法综合评价示例")
    print("=" * 60)
    
    # 示例:评价5个城市的经济发展水平
    cities = ['北京', '上海', '广州', '深圳', '杭州']
    indicators = ['GDP(万亿)', '人均收入(万)', '失业率(%)', '环境指数', '创新指数']
    
    # 指标方向:1为正向(越大越好),-1为负向(越小越好)
    directions = [1, 1, -1, 1, 1]  # 失业率是负向指标
    
    # 数据矩阵
    data = np.array([
        [4.0, 12.5, 3.2, 85, 92],  # 北京
        [4.3, 13.2, 3.5, 80, 88],  # 上海
        [2.8, 10.8, 2.8, 78, 75],  # 广州
        [3.2, 12.0, 2.5, 82, 95],  # 深圳
        [1.8, 11.5, 2.9, 88, 85],  # 杭州
    ])
    
    print("\n评价对象:", cities)
    print("评价指标:", indicators)
    print("指标方向:", ['正向' if d == 1 else '负向' for d in directions])
    
    print("\n原始数据:")
    print("        ", "  ".join([f"{ind:12s}" for ind in indicators]))
    for city, row in zip(cities, data):
        print(f"{city:6s}:", "  ".join([f"{val:12.1f}" for val in row]))
    
    # 计算熵权
    ewm = EntropyWeightMethod()
    scores, weights, entropy, utility, normalized = ewm.evaluate(data, directions)
    
    print("\n" + "=" * 60)
    print("分析结果")
    print("=" * 60)
    
    print("\n指标信息熵:")
    for indicator, e in zip(indicators, entropy):
        print(f"  {indicator}: {e:.4f}")
    
    print("\n信息效用值:")
    for indicator, u in zip(indicators, utility):
        print(f"  {indicator}: {u:.4f}")
    
    print("\n指标权重:")
    for indicator, weight in zip(indicators, weights):
        print(f"  {indicator}: {weight:.4f}")
    
    print("\n综合得分:")
    for city, score in zip(cities, scores):
        print(f"  {city}: {score:.4f}")
    
    # 排序
    ranking = np.argsort(-scores)
    print("\n城市排名:")
    for i, idx in enumerate(ranking):
        print(f"  第{i+1}名: {cities[idx]} (得分: {scores[idx]:.4f})")
    
    # 可视化
    visualize_entropy_results(data, weights, entropy, utility, normalized, 
                             cities, indicators, directions)
```

---

## 4. 优劣解距离法 (TOPSIS)

### 算法介绍

TOPSIS(Technique for Order Preference by Similarity to Ideal Solution)通过计算各方案与最优解和最劣解的距离进行排序。

#### 4.1 数据标准化

**向量标准化**:
$$
r_{ij} = \frac{x_{ij}}{\sqrt{\sum_{i=1}^{m} x_{ij}^2}}
$$

#### 4.2 构建加权规范化矩阵

$$
v_{ij} = w_j \cdot r_{ij}
$$

其中$w_j$是指标权重(可用熵权法、AHP等确定)。

#### 4.3 确定正理想解和负理想解

**正理想解**:
$$
V^+ = \{v_1^+, v_2^+, \ldots, v_n^+\}
$$

其中:
- 正向指标:$v_j^+ = \max_i \{v_{ij}\}$
- 负向指标:$v_j^+ = \min_i \{v_{ij}\}$

**负理想解**:
$$
V^- = \{v_1^-, v_2^-, \ldots, v_n^-\}
$$

其中:
- 正向指标:$v_j^- = \min_i \{v_{ij}\}$
- 负向指标:$v_j^- = \max_i \{v_{ij}\}$

#### 4.4 计算距离

**到正理想解的距离**:
$$
D_i^+ = \sqrt{\sum_{j=1}^{n} (v_{ij} - v_j^+)^2}
$$

**到负理想解的距离**:
$$
D_i^- = \sqrt{\sum_{j=1}^{n} (v_{ij} - v_j^-)^2}
$$

#### 4.5 计算相对贴近度

$$
C_i = \frac{D_i^-}{D_i^+ + D_i^-}
$$

$C_i \in [0, 1]$,值越大说明方案越优。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 方案排序 | 多方案排序比较 | 需要完整排序 |
| 绩效评价 | 企业/地区绩效评价 | 多指标评价 |
| 风险评估 | 项目风险评价 | 风险排序 |
| 质量评价 | 产品质量评价 | 质量排序 |
| 供应商选择 | 供应商评价排序 | 供应商排序 |

### 可视化图表类型

- **贴近度对比图**:各方案贴近度对比
- **理想解距离图**:到正负理想解的距离
- **二维散点图**:$(D^+, D^-)$散点图
- **权重敏感性图**:权重变化对排序的影响
- **雷达图**:各方案指标得分对比

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Multiple Attribute Decision Making | Hwang & Yoon | 1981 | Springer |
| TOPSIS for Multiple Objective Decision Making | Yoon | 1987 | PhD Thesis |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体 - 多字体备选防止渲染问题
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans', 'Arial Unicode MS', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False

class TOPSISAnalyzer:
    """
    TOPSIS综合评价分析类
    """
    
    @staticmethod
    def evaluate(data, weights, directions=None):
        """
        TOPSIS综合评价
        :param data: 数据矩阵 (样本×指标)
        :param weights: 指标权重向量
        :param directions: 指标方向,1为正向,-1为负向
        :return: 相对贴近度, 到正理想解距离, 到负理想解距离, 排序结果, 正理想解, 负理想解, 加权标准化数据
        """
        data = np.array(data, dtype=float)
        weights = np.array(weights)
        m, n = data.shape

        if directions is None:
            directions = np.ones(n)
        else:
            directions = np.array(directions)

        # 向量标准化
        normalized = data / np.sqrt((data ** 2).sum(axis=0))

        # 加权规范化
        weighted = normalized * weights

        # 确定正负理想解
        v_positive = np.zeros(n)
        v_negative = np.zeros(n)

        for j in range(n):
            if directions[j] == 1:  # 正向指标
                v_positive[j] = weighted[:, j].max()
                v_negative[j] = weighted[:, j].min()
            else:  # 负向指标
                v_positive[j] = weighted[:, j].min()
                v_negative[j] = weighted[:, j].max()

        # 计算距离
        d_positive = np.sqrt(((weighted - v_positive) ** 2).sum(axis=1))
        d_negative = np.sqrt(((weighted - v_negative) ** 2).sum(axis=1))

        # 计算相对贴近度
        closeness = d_negative / (d_positive + d_negative + 1e-10)
        
        # 排序
        ranking = np.argsort(-closeness)

        return closeness, d_positive, d_negative, ranking, v_positive, v_negative, weighted

def visualize_topsis_results(data, weights, directions, closeness, d_positive, d_negative, 
                             ranking, v_positive, v_negative, weighted,
                             sample_names=None, indicator_names=None):
    """可视化TOPSIS分析结果"""
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 2, height_ratios=[1, 1, 1])
    
    m, n = data.shape
    if sample_names is None:
        sample_names = [f'样本{i+1}' for i in range(m)]
    if indicator_names is None:
        indicator_names = [f'指标{i+1}' for i in range(n)]
    
    # 图1:加权标准化数据热力图
    ax1 = fig.add_subplot(gs[0, 0])
    im1 = ax1.imshow(weighted, cmap='RdYlGn', aspect='auto')
    
    for i in range(m):
        for j in range(n):
            text = ax1.text(j, i, f'{weighted[i, j]:.3f}',
                          ha="center", va="center", color="black", fontsize=8)
    
    ax1.set_xticks(range(n))
    ax1.set_yticks(range(m))
    ax1.set_xticklabels(indicator_names, rotation=45, ha='right')
    ax1.set_yticklabels(sample_names)
    ax1.set_title('加权标准化数据矩阵', fontsize=14)
    plt.colorbar(im1, ax=ax1)
    
    # 图2:理想解对比
    ax2 = fig.add_subplot(gs[0, 1])
    x = np.arange(n)
    width = 0.35
    bars1 = ax2.bar(x - width/2, v_positive, width, label='正理想解', color='green', alpha=0.7, edgecolor='black')
    bars2 = ax2.bar(x + width/2, v_negative, width, label='负理想解', color='red', alpha=0.7, edgecolor='black')
    ax2.set_xlabel('指标', fontsize=12)
    ax2.set_ylabel('加权标准化值', fontsize=12)
    ax2.set_title('正理想解与负理想解对比', fontsize=14)
    ax2.set_xticks(x)
    ax2.set_xticklabels(indicator_names, rotation=45, ha='right')
    ax2.legend()
# 图3:距离分析
    ax3 = fig.add_subplot(gs[1, 0])
    x = np.arange(m)
    width = 0.35
    bars1 = ax3.bar(x - width/2, d_positive, width, label='到正理想解距离', color='lightcoral', edgecolor='black')
    bars2 = ax3.bar(x + width/2, d_negative, width, label='到负理想解距离', color='lightblue', edgecolor='black')
    ax3.set_xlabel('样本', fontsize=12)
    ax3.set_ylabel('欧氏距离', fontsize=12)
    ax3.set_title('各样本到理想解的距离', fontsize=14)
    ax3.set_xticks(x)
    ax3.set_xticklabels(sample_names, rotation=45, ha='right')
    ax3.legend()
# 图4:相对贴近度
    ax4 = fig.add_subplot(gs[1, 1])
    colors = plt.cm.RdYlGn(closeness)
    bars = ax4.barh(sample_names, closeness, color=colors, edgecolor='black')
    for bar, ci in zip(bars, closeness):
        width = bar.get_width()
        ax4.text(width, bar.get_y() + bar.get_height()/2, 
                f'{ci:.4f}', ha='left', va='center', fontsize=10)
    ax4.set_xlabel('相对贴近度 C', fontsize=12)
    ax4.set_title('TOPSIS相对贴近度', fontsize=14)
    ax4.set_xlim(0, 1)
    
    # 图5:综合排名
    ax5 = fig.add_subplot(gs[2, :])
    sorted_indices = ranking
    sorted_c = closeness[sorted_indices]
    sorted_names = [sample_names[i] for i in sorted_indices]
    colors_rank = plt.cm.RdYlGn(sorted_c)
    bars = ax5.barh(range(m), sorted_c[::-1], color=colors_rank[::-1], edgecolor='black')
    for i, (bar, ci) in enumerate(zip(bars, sorted_c[::-1])):
        width = bar.get_width()
        rank = m - i
        ax5.text(width + 0.01, bar.get_y() + bar.get_height()/2, 
                f'第{rank}名: {ci:.4f}', ha='left', va='center', fontsize=10)
    ax5.set_yticks(range(m))
    ax5.set_yticklabels(sorted_names[::-1])
    ax5.set_xlabel('相对贴近度 C', fontsize=12)
    ax5.set_title('TOPSIS综合评价排名', fontsize=14)
    ax5.set_xlim(0, 1.2)
    
    plt.tight_layout()
    plt.savefig('topsis_analysis_results.png', dpi=150, bbox_inches='tight')
    plt.show()
    print("\n图表已保存为 'topsis_analysis_results.png'")

# 运行示例
if __name__ == "__main__":
    print("=" * 60)
    print("TOPSIS综合评价示例")
    print("=" * 60)
    
    # 示例:选择最佳供应商
    suppliers = ['供应商A', '供应商B', '供应商C', '供应商D', '供应商E']
    indicators = ['价格', '质量', '交货期', '服务', '信誉']
    directions = [-1, 1, 1, 1, 1]  # 价格越低越好
    weights = [0.25, 0.30, 0.20, 0.15, 0.10]
    
    data = np.array([
        [100, 85, 15, 90, 88],
        [120, 92, 12, 85, 90],
        [90, 78, 18, 88, 82],
        [110, 88, 14, 92, 85],
        [95, 82, 16, 87, 80],
    ])
    
    print("\n评价对象:", suppliers)
    print("评价指标:", indicators)
    print("指标权重:", [f"{ind}:{w:.2f}" for ind, w in zip(indicators, weights)])
    
    topsis = TOPSISAnalyzer()
    closeness, d_pos, d_neg, ranking, v_pos, v_neg, weighted = topsis.evaluate(
        data, weights, directions
    )
    
    print("\n" + "=" * 60)
    print("TOPSIS分析结果")
    print("=" * 60)
    
    for i, supplier in enumerate(suppliers):
        print(f"\n{supplier}: C = {closeness[i]:.4f}")
    
    print("\n推荐排序:")
    for i, idx in enumerate(ranking):
        print(f"  第{i+1}名: {suppliers[idx]} (C = {closeness[idx]:.4f})")
    
    visualize_topsis_results(data, weights, directions, closeness, d_pos, d_neg,
                            ranking, v_pos, v_neg, weighted, suppliers, indicators)
```

---

## 5. 灰色关联分析 (Grey Relational Analysis, GRA)

### 算法介绍

灰色关联分析用于分析各因素之间的关联程度,通过计算关联系数和关联度进行评价。

#### 5.1 确定参考序列和比较序列

**参考序列**(最优序列):
$$
X_0 = \{x_0(1), x_0(2), \ldots, x_0(n)\}
$$

通常选择各指标的最优值组成参考序列。

**比较序列**:
$$
X_i = \{x_i(1), x_i(2), \ldots, x_i(n)\}, \quad i = 1, 2, \ldots, m
$$

#### 5.2 数据无量纲化

**初值化**:$x_i'(k) = x_i(k) / x_i(1)$

**均值化**:$x_i'(k) = x_i(k) / \bar{x}_i$

**区间化**:$x_i'(k) = \frac{x_i(k) - \min_k x_i(k)}{\max_k x_i(k) - \min_k x_i(k)}$

#### 5.3 计算关联系数

$$
\xi_i(k) = \frac{\min_i \min_k |x_0(k) - x_i(k)| + \rho \max_i \max_k |x_0(k) - x_i(k)|}{|x_0(k) - x_i(k)| + \rho \max_i \max_k |x_0(k) - x_i(k)|}
$$

其中$\rho$是分辨系数,通常取0.5。

#### 5.4 计算关联度

$$
\gamma_i = \frac{1}{n} \sum_{k=1}^{n} \xi_i(k)
$$

关联度越大,说明该序列与参考序列的关联程度越高,方案越优。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 因素分析 | 影响因素分析 | 因素关联 |
| 方案评价 | 多方案评价 | 小样本 |
| 模式识别 | 模式分类识别 | 关联度分类 |
| 趋势分析 | 发展趋势关联 | 时序关联 |
| 风险评估 | 风险因素分析 | 风险关联 |

### 可视化图表类型

- **关联系数热力图**:各点关联系数
- **关联度排序图**:各序列关联度排序
- **序列曲线图**:参考序列与比较序列
- **分辨系数敏感性图**:ρ对关联度的影响
- **趋势关联图**:时间序列关联分析

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| 灰色系统理论教程 | 邓聚龙 | 1990 | 华中理工大学出版社 |
| Grey System Theory and Applications | Liu & Lin | 2006 | Springer |

### 代码实现要点

```python
import numpy as np

def grey_relational_analysis(data, reference=None, rho=0.5):
    """
    灰色关联分析
    :param data: 比较序列矩阵 (样本×指标)
    :param reference: 参考序列,若为None则取各列最优值
    :param rho: 分辨系数
    :return: 关联度, 关联系数矩阵
    """
    data = np.array(data, dtype=float)
    m, n = data.shape

    # 确定参考序列
    if reference is None:
        reference = data.max(axis=0)  # 取各列最大值
    else:
        reference = np.array(reference)

    # 区间化无量纲
    min_vals = data.min(axis=0)
    max_vals = data.max(axis=0)
    ranges = max_vals - min_vals
    ranges[ranges == 0] = 1  # 避免除零

    normalized = (data - min_vals) / ranges
    ref_normalized = (reference - min_vals) / ranges

    # 计算差序列
    diff = np.abs(normalized - ref_normalized)

    # 计算关联系数
    min_diff = diff.min()
    max_diff = diff.max()

    grey_relational_coefficients = (min_diff + rho * max_diff) / (diff + rho * max_diff)

    # 计算关联度
    grey_relational_grades = grey_relational_coefficients.mean(axis=1)

    return grey_relational_grades, grey_relational_coefficients
```

---

## 6. 秩和比法 (Rank Sum Ratio, RSR)

### 算法介绍

秩和比法是一种将多指标转化为秩次(排名)进行综合评价的方法,计算简单,适用范围广。

#### 6.1 编秩

**编秩规则**:

| 指标类型 | 编秩方法 |
|---------|---------|
| 高优指标(越大越好) | 按升序编秩:最小值编1,次小编2,... |
| 低优指标(越小越好) | 按降序编秩:最大值编1,次大编2,... |

**相同数值**:取平均秩次。

#### 6.2 计算秩和比

$$
RSR_i = \frac{1}{m \cdot n} \sum_{j=1}^{n} R_{ij}
$$

其中$m$是样本数,$n$是指标数,$R_{ij}$是方案$i$在指标$j$上的秩次。

$RSR_i \in [1/m, 1]$,值越大说明方案越优。

#### 6.3 分档评价(可选)

根据RSR值进行分档:

| 分档 | RSR范围 |
|------|---------|
| 上等 | $RSR \geq \bar{x} + 0.5s$ |
| 中等 | $\bar{x} - 0.5s < RSR < \bar{x} + 0.5s$ |
| 下等 | $RSR \leq \bar{x} - 0.5s$ |

其中$\bar{x}$和$s$分别是RSR的均值和标准差。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 卫生统计 | 医疗质量评价 | 秩次数据 |
| 教育评价 | 学校/地区教育水平 | 排名数据 |
| 体育竞技 | 运动员/球队排名 | 竞技排名 |
| 综合评价 | 多指标综合评价 | 指标单位不同 |
| 方案排序 | 多方案比较排序 | 需要排序 |

### 可视化图表类型

- **RSR值对比图**:各方案RSR值
- **分档直方图**:RSR分档分布
- **秩次热力图**:秩次矩阵可视化
- **排序对比图**:RSR排序与其他方法对比
- **箱线图**:RSR值分布

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| 秩和比法及其应用 | 田凤调 | 1995 | 中国卫生统计 |
| Rank Sum Ratio Method | Tian Fengtiao | 2002 | Chinese Journal of Health Statistics |

### 代码实现要点

```python
import numpy as np
import pandas as pd

def rank_sum_ratio(data, directions=None):
    """
    秩和比法
    :param data: 数据矩阵 (样本×指标)
    :param directions: 指标方向,1为高优,-1为低优
    :return: RSR值, 秩次矩阵
    """
    data = np.array(data)
    m, n = data.shape

    if directions is None:
        directions = np.ones(n)
    else:
        directions = np.array(directions)

    # 编秩
    ranks = np.zeros((m, n))
    for j in range(n):
        if directions[j] == 1:  # 高优指标
            # 升序排名
            rank_values = pd.Series(data[:, j]).rank(method='average')
        else:  # 低优指标
            # 降序排名(取负后排名)
            rank_values = pd.Series(-data[:, j]).rank(method='average')
        ranks[:, j] = rank_values.values

    # 计算RSR
    rsr = ranks.sum(axis=1) / (m * n)

    return rsr, ranks

def rsr_classification(rsr):
    """
    RSR分档评价
    :param rsr: RSR值数组
    :return: 各样本分档结果
    """
    mean_rsr = rsr.mean()
    std_rsr = rsr.std()

    classifications = []
    for value in rsr:
        if value >= mean_rsr + 0.5 * std_rsr:
            classifications.append('上等')
        elif value <= mean_rsr - 0.5 * std_rsr:
            classifications.append('下等')
        else:
            classifications.append('中等')

    return classifications
```

---

## 7. 变异系数法 (Coefficient of Variation Method)

### 算法介绍

变异系数法是一种客观赋权方法,根据各指标的变异程度确定权重。变异程度越大,说明该指标区分能力越强,权重越大。

#### 7.1 数据标准化

**标准化**:
$$
r_{ij} = \frac{x_{ij} - \bar{x}_j}{s_j}
$$

其中$\bar{x}_j$和$s_j$分别是指标$j$的均值和标准差。

#### 7.2 计算变异系数

$$
CV_j = \frac{s_j}{|\bar{x}_j|}
$$

为避免均值接近0的情况,可使用:
$$
CV_j = \frac{s_j}{\bar{x}_j + \varepsilon}
$$

其中$\varepsilon$是一个小正数。

#### 7.3 计算权重

$$
w_j = \frac{CV_j}{\sum_{k=1}^{n} CV_k}
$$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 综合评价 | 多指标综合评价 | 数据变异差异大 |
| 方案选优 | 最佳方案选择 | 客观赋权 |
| 绩效评估 | 地区/企业绩效 | 数据驱动 |
| 质量评价 | 产品质量评价 | 区分度要求高 |
| 风险评估 | 项目风险评价 | 变异性重要 |

### 可视化图表类型

- **变异系数对比图**:各指标CV值
- **权重分布图**:各指标权重
- **数据分布箱线图**:各指标数据分布
- **标准化数据图**:标准化后的数据
- **敏感性分析图**:数据变化对权重影响

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Statistical Methods | Snedecor & Cochran | 1989 | Iowa State University Press |

### 代码实现要点

```python
import numpy as np

def coefficient_of_variation_weight(data):
    """
    变异系数法计算权重
    :param data: 数据矩阵 (样本×指标)
    :return: 权重向量, 变异系数
    """
    data = np.array(data, dtype=float)
    m, n = data.shape

    # 计算均值和标准差
    means = data.mean(axis=0)
    stds = data.std(axis=0, ddof=1)

    # 计算变异系数
    cvs = stds / np.abs(means)
    cvs[np.isnan(cvs)] = 0  # 处理均值为0的情况

    # 计算权重
    weights = cvs / cvs.sum()

    return weights, cvs

def cv_evaluation(data):
    """
    变异系数法综合评价
    :param data: 数据矩阵 (样本×指标)
    :return: 各样本综合得分
    """
    weights, _ = coefficient_of_variation_weight(data)

    # 数据标准化
    means = data.mean(axis=0)
    stds = data.std(axis=0, ddof=1)
    normalized = (data - means) / stds

    # 计算综合得分
    scores = normalized @ weights

    return scores, weights
```

---

## 8. 主观赋权法

### 算法介绍

主观赋权法根据决策者的主观判断确定权重,主要包括直接打分法、专家调查法、德尔菲法等。

#### 8.1 直接打分法

专家直接给出各指标的权重或分数,然后进行综合。

**权重归一化**:
$$
w_j = \frac{S_j}{\sum_{k=1}^{n} S_k}
$$

其中$S_j$是指标$j$的专家打分。

#### 8.2 专家调查法

1. 邀请$k$位专家
2. 每位专家给出权重$w_j^{(i)}$
3. 综合计算权重:$w_j = \frac{1}{k} \sum_{i=1}^{k} w_j^{(i)}$

#### 8.3 德尔菲法

1. 匿名征求专家意见
2. 统计反馈给专家
3. 专家修改意见
4. 重复2-3步直至收敛

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 战略决策 | 战略方案选择 | 主观性强 |
| 政策评估 | 政策效果评价 | 经验重要 |
| 人才评价 | 人才选拔评价 | 定性为主 |
| 价值评估 | 项目价值评估 | 价值判断 |
| 风险评估 | 项目风险评价 | 专家经验 |

### 可视化图表类型

- **权重分布图**:各指标权重
- **专家意见对比图**:各专家意见对比
- **意见收敛图**:德尔菲法意见收敛
- **一致性分析图**:专家意见一致性
- **权重区间图**:权重置信区间

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| The Delphi Method | Dalkey & Helmer | 1963 | RAND Corporation |

### 代码实现要点

```python
import numpy as np

def direct_scoring_weight(scores):
    """
    直接打分法计算权重
    :param scores: 指标得分向量
    :return: 归一化权重
    """
    scores = np.array(scores)
    weights = scores / scores.sum()
    return weights

def expert_survey_weight(expert_weights):
    """
    专家调查法计算权重
    :param expert_weights: 专家权重矩阵 (专家×指标)
    :return: 综合权重, 各专家权重
    """
    expert_weights = np.array(expert_weights)
    # 确保每行归一化
    expert_weights = expert_weights / expert_weights.sum(axis=1, keepdims=True)

    # 计算平均权重
    mean_weights = expert_weights.mean(axis=0)

    return mean_weights, expert_weights

def delphi_method(initial_weights, max_rounds=3, convergence_threshold=0.1):
    """
    德尔菲法模拟(简化版)
    :param initial_weights: 初始专家权重矩阵 (专家×指标)
    :param max_rounds: 最大轮数
    :param convergence_threshold: 收敛阈值
    :return: 最终权重, 每轮权重历史
    """
    weights_history = [initial_weights.copy()]
    current_weights = initial_weights.copy()

    for round_num in range(max_rounds - 1):
        # 计算上一轮的平均权重(反馈给专家)
        mean_weights = current_weights.mean(axis=0)

        # 专家根据反馈调整权重(这里用简单模拟:向均值靠近)
        adjustment_rate = 0.3
        new_weights = current_weights + adjustment_rate * (mean_weights - current_weights)

        # 归一化
        new_weights = new_weights / new_weights.sum(axis=1, keepdims=True)

        current_weights = new_weights
        weights_history.append(current_weights.copy())

        # 检查收敛
        std = current_weights.std(axis=0).mean()
        if std < convergence_threshold:
            break

    final_weights = current_weights.mean(axis=0)

    return final_weights, weights_history
```

---

## 9. 数据包络分析 (Data Envelopment Analysis, DEA)

### 算法介绍

数据包络分析是一种用于评价多输入多输出系统相对效率的非参数方法,广泛应用于效率评价和生产力分析。

#### 9.1 基本概念

**决策单元(DMU)**:被评价的单位(如企业、银行、学校等)

**投入指标**:$X = (x_1, x_2, \ldots, x_m)^T$

**产出指标**:$Y = (y_1, y_2, \ldots, y_s)^T$

**效率值**:$\theta \in [0, 1]$,$\theta = 1$表示DEA有效(最优效率)

#### 9.2 CCR模型(Charnes-Cooper-Rhodes)

**基于规模报酬不变的DEA模型**:

**规划问题**(投入导向):
$$
\begin{aligned}
\min \quad & \theta \\
\text{s.t.} \quad & \sum_{j=1}^{n} \lambda_j x_{ij} \leq \theta x_{i0}, \quad i = 1, \ldots, m \\
& \sum_{j=1}^{n} \lambda_j y_{rj} \geq y_{r0}, \quad r = 1, \ldots, s \\
& \lambda_j \geq 0, \quad j = 1, \ldots, n
\end{aligned}
$$

其中$\lambda_j$是权重,$(x_{i0}, y_{r0})$是被评价DMU的投入产出。

**对偶模型**:
$$
\begin{aligned}
\max \quad & \theta = \sum_{r=1}^{s} u_r y_{r0} \\
\text{s.t.} \quad & \sum_{r=1}^{s} u_r y_{rj} - \sum_{i=1}^{m} v_i x_{ij} \leq 0, \quad j = 1, \ldots, n \\
& \sum_{i=1}^{m} v_i x_{i0} = 1 \\
& u_r, v_i \geq \varepsilon > 0
\end{aligned}
$$

#### 9.3 BCC模型(Banker-Charnes-Cooper)

**基于规模报酬可变的DEA模型**:

添加约束:$\sum_{j=1}^{n} \lambda_j = 1$

**纯技术效率**:PTE = $\theta_{BCC}$

**规模效率**:SE = $\theta_{CCR} / \theta_{BCC}$

#### 9.4 超效率DEA模型

用于DEA有效DMU的进一步排序:

$$
\begin{aligned}
\min \quad & \theta \\
\text{s.t.} \quad & \sum_{j \neq 0} \lambda_j x_{ij} \leq \theta x_{i0} \\
& \sum_{j \neq 0} \lambda_j y_{rj} \geq y_{r0} \\
& \lambda_j \geq 0
\end{aligned}
$$

#### 9.5 Malmquist指数

**全要素生产率变化指数**:
$$
M = \sqrt{\frac{D^t(x^{t+1}, y^{t+1})}{D^t(x^t, y^t)} \cdot \frac{D^{t+1}(x^{t+1}, y^{t+1})}{D^{t+1}(x^t, y^t)}}
$$

分解为:$M = EC \cdot TC$(效率变化 × 技术变化)

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 效率评价 | 企业/银行效率评价 | 多投入多产出 |
| 生产力分析 | 全要素生产率 | 面板数据 |
| 绩效评估 | 医院/学校绩效 | 相对效率 |
| 能源效率 | 区域能源效率 | 环境评价 |
| 项目评估 | 项目相对效率 | 无需预设函数 |

### 可视化图表类型

- **效率值柱状图**:各DMU效率值
- **前沿面图**:有效前沿面与DMU位置
- **投入产出散点图**:投入与产出关系
- **Malmquist指数图**:全要素生产率变化
- **松弛变量图**:投入冗余与产出不足

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Measuring the efficiency of decision making units | Charnes et al. | 1978 | European Journal of Operational Research |
| Some models for estimating technical and scale inefficiencies | Banker et al. | 1984 | Management Science |

### 代码实现要点

```python
import numpy as np
from scipy.optimize import linprog

def dea_ccr(inputs, outputs, orientation='input'):
    """
    CCR模型(投入导向或产出导向)
    :param inputs: 投入矩阵 (n_dmus, n_inputs)
    :param outputs: 产出矩阵 (n_dmus, n_outputs)
    :param orientation: 'input'投入导向或'output'产出导向
    :return: 效率值数组
    """
    inputs = np.array(inputs, dtype=float)
    outputs = np.array(outputs, dtype=float)
    n_dmus, n_inputs = inputs.shape
    n_outputs = outputs.shape[1]

    efficiencies = []

    for k in range(n_dmus):
        # 被评价DMU
        x0 = inputs[k]
        y0 = outputs[k]

        if orientation == 'input':
            # 投入导向:最小化theta
            c = np.array([1] + [0] * n_dmus)
            A_ub = np.zeros((n_inputs + n_outputs, 1 + n_dmus))
            b_ub = np.zeros(n_inputs + n_outputs)

            # 投入约束: sum(lambda_j * x_ij) <= theta * x_i0
            for i in range(n_inputs):
                A_ub[i, 0] = x0[i]
                A_ub[i, 1:] = inputs[:, i]
                b_ub[i] = 0

            # 产出约束: sum(lambda_j * y_rj) >= y_r0
            for r in range(n_outputs):
                A_ub[n_inputs + r, 1:] = -outputs[:, r]
                b_ub[n_inputs + r] = -y0[r]

            bounds = [(None, None)] + [(0, None)] * n_dmus

        else:  # 产出导向
            # 产出导向:最大化phi(相当于最小化1/phi)
            c = np.array([-1] + [0] * n_dmus)
            A_ub = np.zeros((n_inputs + n_outputs, 1 + n_dmus))
            b_ub = np.zeros(n_inputs + n_outputs)

            # 投入约束
            for i in range(n_inputs):
                A_ub[i, 1:] = inputs[:, i]
                b_ub[i] = x0[i]

            # 产出约束
            for r in range(n_outputs):
                A_ub[n_inputs + r, 0] = y0[r]
                A_ub[n_inputs + r, 1:] = -outputs[:, r]
                b_ub[n_inputs + r] = 0

            bounds = [(None, None)] + [(0, None)] * n_dmus

        res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs')

        if orientation == 'input':
            efficiencies.append(res.fun if res.success else np.nan)
        else:
            efficiencies.append(1 / res.fun if res.success and res.fun > 0 else np.nan)

    return np.array(efficiencies)

def dea_bcc(inputs, outputs, orientation='input'):
    """
    BCC模型(规模报酬可变)
    :param inputs: 投入矩阵 (n_dmus, n_inputs)
    :param outputs: 产出矩阵 (n_dmus, n_outputs)
    :param orientation: 'input'投入导向或'output'产出导向
    :return: 技术效率值, 规模效率值
    """
    inputs = np.array(inputs, dtype=float)
    outputs = np.array(outputs, dtype=float)
    n_dmus = inputs.shape[0]

    ccr_eff = dea_ccr(inputs, outputs, orientation)
    bcc_eff = []

    for k in range(n_dmus):
        x0 = inputs[k]
        y0 = outputs[k]
        n_inputs = inputs.shape[1]
        n_outputs = outputs.shape[1]

        if orientation == 'input':
            c = np.array([1] + [0] * n_dmus)
            A_ub = np.zeros((n_inputs + n_outputs, 1 + n_dmus))
            b_ub = np.zeros(n_inputs + n_outputs)

            for i in range(n_inputs):
                A_ub[i, 0] = x0[i]
                A_ub[i, 1:] = inputs[:, i]
                b_ub[i] = 0

            for r in range(n_outputs):
                A_ub[n_inputs + r, 1:] = -outputs[:, r]
                b_ub[n_inputs + r] = -y0[r]

            # 凸性约束: sum(lambda) = 1
            A_eq = np.array([[0] + [1] * n_dmus])
            b_eq = np.array([1])

            bounds = [(None, None)] + [(0, None)] * n_dmus

            res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')
            bcc_eff.append(res.fun if res.success else np.nan)

    bcc_eff = np.array(bcc_eff)
    scale_eff = ccr_eff / (bcc_eff + 1e-10)  # 规模效率

    return bcc_eff, scale_eff

def dea_super_efficiency(inputs, outputs):
    """
    超效率DEA模型
    :param inputs: 投入矩阵
    :param outputs: 产出矩阵
    :return: 超效率值
    """
    inputs = np.array(inputs, dtype=float)
    outputs = np.array(outputs, dtype=float)
    n_dmus, n_inputs = inputs.shape
    n_outputs = outputs.shape[1]

    super_eff = []

    for k in range(n_dmus):
        x0 = inputs[k]
        y0 = outputs[k]

        # 排除当前DMU
        other_inputs = np.delete(inputs, k, axis=0)
        other_outputs = np.delete(outputs, k, axis=0)
        n_other = n_dmus - 1

        c = np.array([1] + [0] * n_other)
        A_ub = np.zeros((n_inputs + n_outputs, 1 + n_other))
        b_ub = np.zeros(n_inputs + n_outputs)

        for i in range(n_inputs):
            A_ub[i, 0] = x0[i]
            A_ub[i, 1:] = other_inputs[:, i]
            b_ub[i] = 0

        for r in range(n_outputs):
            A_ub[n_inputs + r, 1:] = -other_outputs[:, r]
            b_ub[n_inputs + r] = -y0[r]

        bounds = [(None, None)] + [(0, None)] * n_other

        res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs')
        super_eff.append(res.fun if res.success else np.nan)

    return np.array(super_eff)

def plot_dea_efficiency(efficiencies, dmu_names=None, title="DEA Efficiency Scores"):
    """绘制DEA效率值"""
    import matplotlib.pyplot as plt

    plt.figure(figsize=(10, 6))
    x_pos = np.arange(len(efficiencies))
    plt.bar(x_pos, efficiencies, alpha=0.7)
    plt.axhline(y=1, color='r', linestyle='--', label='Efficiency Frontier')
    plt.xlabel('DMU')
    plt.ylabel('Efficiency Score')
    plt.title(title)
    plt.xticks(x_pos, dmu_names if dmu_names else range(len(efficiencies)))
    plt.legend()
    plt.tight_layout()
    plt.show()
```

---

## 10. 区间数评价

### 算法介绍

区间数评价用于处理指标值为区间数(不确定性)的评价问题,通过区间运算得到评价结果的区间。

#### 10.1 区间数基本运算

**区间数**:$\tilde{a} = [a^L, a^U]$,其中$a^L \leq a^U$

**区间加法**:$\tilde{a} + \tilde{b} = [a^L + b^L, a^U + b^U]$

**区间乘法**:$\tilde{a} \times \tilde{b} = [\min(a^L b^L, a^L b^U, a^U b^L, a^U b^U), \max(a^L b^L, a^L b^U, a^U b^L, a^U b^U)]$

**区间数乘以常数**:$k \cdot \tilde{a} = [k a^L, k a^U]$($k \geq 0$)

#### 10.2 区间数标准化

**正向指标标准化**:
$$
\tilde{r}_{ij} = \left[ \frac{a_{ij}^L}{\max_k a_{kj}^U}, \frac{a_{ij}^U}{\max_k a_{kj}^U} \right]
$$

**负向指标标准化**:
$$
\tilde{r}_{ij} = \left[ \frac{\min_k a_{kj}^L}{a_{ij}^U}, \frac{\min_k a_{kj}^U}{a_{ij}^L} \right]
$$

#### 10.3 区间数TOPSIS

**加权规范化矩阵**:$\tilde{v}_{ij} = w_j \cdot \tilde{r}_{ij}$

**正理想解**:
$$
\tilde{V}^+ = \{ \tilde{v}_1^+, \tilde{v}_2^+, \ldots, \tilde{v}_n^+ \}
$$

**负理想解**:
$$
\tilde{V}^- = \{ \tilde{v}_1^-, \tilde{v}_2^-, \ldots, \tilde{v}_n^- \}
$$

**距离计算**(区间距离):
$$
D(\tilde{a}, \tilde{b}) = \sqrt{(a^L - b^L)^2 + (a^U - b^U)^2}
$$

#### 10.4 区间数排序

**可能度**:区间数$\tilde{a} \geq \tilde{b}$的可能度

$$
P(\tilde{a} \geq \tilde{b}) = \frac{\max(0, a^U - b^L) - \max(0, a^L - b^U)}{(a^U - a^L) + (b^U - b^L)}
$$

**排序方法**:
1. 计算各方案得分区间
2. 计算可能度矩阵
3. 计算排序向量

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 不确定评价 | 指标值为区间 | 数据不确定 |
| 风险评估 | 项目风险区间评价 | 风险区间 |
| 预测评价 | 预测值区间评价 | 预测不确定 |
| 工程设计 | 设计参数区间选择 | 参数区间 |
| 经济分析 | 经济指标区间分析 | 指标波动 |

### 可视化图表类型

- **区间值图**:指标值区间
- **得分区间图**:各方案得分区间
- **可能度热力图**:方案间优势可能度
- **不确定性分析图**:区间宽度分析
- **敏感性分析图**:边界变化对排序影响

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Decision analysis with interval probabilities | Sevastianov | 2007 | International Journal of Approximate Reasoning |
| TOPSIS for multiple attribute decision making | Jahanshahloo et al. | 2006 | Applied Mathematics and Computation |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt

class IntervalNumber:
    """区间数类"""
    def __init__(self, lower, upper):
        self.lower = lower
        self.upper = upper

    def __add__(self, other):
        if isinstance(other, IntervalNumber):
            return IntervalNumber(self.lower + other.lower, self.upper + other.upper)
        else:
            return IntervalNumber(self.lower + other, self.upper + other)

    def __mul__(self, scalar):
        return IntervalNumber(self.lower * scalar, self.upper * scalar)

    def __repr__(self):
        return f"[{self.lower:.4f}, {self.upper:.4f}]"

    def midpoint(self):
        """区间中点"""
        return (self.lower + self.upper) / 2

    def width(self):
        """区间宽度"""
        return self.upper - self.lower

    def distance(self, other):
        """区间距离"""
        return np.sqrt((self.lower - other.lower)**2 + (self.upper - other.upper)**2)

def interval_normalize(data, directions=None):
    """
    区间数数据标准化
    :param data: 区间数数据矩阵 [(lower, upper), ...]
    :param directions: 指标方向
    :return: 标准化后的区间数矩阵
    """
    data = np.array(data)
    n_samples, n_cols = data.shape

    if directions is None:
        directions = np.ones(n_cols)
    else:
        directions = np.array(directions)

    normalized = []
    for j in range(n_cols):
        col = data[:, j]
        lowers = col[:, 0] if col.ndim > 1 else np.array([x[0] for x in col])
        uppers = col[:, 1] if col.ndim > 1 else np.array([x[1] for x in col])

        if directions[j] == 1:  # 正向指标
            max_upper = uppers.max()
            norm_col = [IntervalNumber(l / max_upper, u / max_upper) for l, u in zip(lowers, uppers)]
        else:  # 负向指标
            min_lower = lowers.min()
            norm_col = [IntervalNumber(min_lower / u, min_lower / l) for l, u in zip(lowers, uppers)]

        normalized.append(norm_col)

    return np.column_stack(normalized)

def interval_topsis(data, weights, directions=None):
    """
    区间数TOPSIS
    :param data: 区间数数据矩阵
    :param weights: 权重向量
    :param directions: 指标方向
    :return: 各方案贴近度区间
    """
    data = np.array(data)
    n_samples, n_cols = data.shape
    weights = np.array(weights)

    # 标准化
    normalized = interval_normalize(data, directions)

    # 加权
    weighted = []
    for i in range(n_samples):
        row = []
        for j in range(n_cols):
            row.append(normalized[i, j] * weights[j])
        weighted.append(row)

    # 确定正负理想解
    v_positive = []
    v_negative = []
    for j in range(n_cols):
        col = [weighted[i][j] for i in range(n_samples)]

        if directions is None or directions[j] == 1:
            v_positive.append(IntervalNumber(max([x.lower for x in col]),
                                           max([x.upper for x in col])))
            v_negative.append(IntervalNumber(min([x.lower for x in col]),
                                           min([x.upper for x in col])))
        else:
            v_positive.append(IntervalNumber(min([x.lower for x in col]),
                                           min([x.upper for x in col])))
            v_negative.append(IntervalNumber(max([x.lower for x in col]),
                                           max([x.upper for x in col])))

    # 计算距离
    d_positive = []
    d_negative = []
    for i in range(n_samples):
        dp = np.sqrt(sum([weighted[i][j].distance(v_positive[j])**2 for j in range(n_cols)]))
        dn = np.sqrt(sum([weighted[i][j].distance(v_negative[j])**2 for j in range(n_cols)]))
        d_positive.append(dp)
        d_negative.append(dn)

    # 计算贴近度(作为区间)
    closeness_intervals = []
    for i in range(n_samples):
        c_lower = d_negative[i] / (d_positive[i] + d_negative[i] + 1e-10)
        c_upper = d_negative[i] / (d_positive[i] + d_negative[i] + 1e-10)
        # 考虑区间运算的不确定性
        width = (weighted[i][0].width() if hasattr(weighted[i][0], 'width') else 0)
        closeness_intervals.append(IntervalNumber(max(0, c_lower - width/2), min(1, c_upper + width/2)))

    return closeness_intervals

def interval_possibility(interval_a, interval_b):
    """
    计算区间a >= b的可能度
    :param interval_a: 区间a
    :param interval_b: 区间b
    :return: 可能度值
    """
    a_l, a_u = interval_a.lower, interval_a.upper
    b_l, b_u = interval_b.lower, interval_b.upper

    numerator = max(0, a_u - b_l) - max(0, a_l - b_u)
    denominator = (a_u - a_l) + (b_u - b_l)

    if denominator == 0:
        return 0.5

    return numerator / denominator

def interval_ranking(intervals):
    """
    区间数排序
    :param intervals: 区间数列表
    :return: 排序索引, 可能度矩阵
    """
    n = len(intervals)

    # 计算可能度矩阵
    possibility_matrix = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            if i == j:
                possibility_matrix[i, j] = 0.5
            else:
                possibility_matrix[i, j] = interval_possibility(intervals[i], intervals[j])

    # 计算排序向量
    ranking_vector = possibility_matrix.sum(axis=1) / n

    # 排序
    sorted_indices = np.argsort(-ranking_vector)

    return sorted_indices, possibility_matrix, ranking_vector

def plot_interval_scores(intervals, labels=None, title="Interval Scores"):
    """绘制区间得分"""
    fig, ax = plt.subplots(figsize=(10, 6))

    n = len(intervals)
    x_pos = np.arange(n)

    midpoints = [iv.midpoint() for iv in intervals]
    lowers = [iv.lower for iv in intervals]
    uppers = [iv.upper for iv in intervals]

    # 绘制误差条
    ax.errorbar(x_pos, midpoints,
                yerr=[np.array(midpoints) - np.array(lowers),
                      np.array(uppers) - np.array(midpoints)],
                fmt='o', capsize=5, capthick=2, linewidth=2)

    ax.set_xlabel('Alternative')
    ax.set_ylabel('Score')
    ax.set_title(title)
    ax.set_xticks(x_pos)
    ax.set_xticklabels(labels if labels else range(n))
    plt.tight_layout()
    plt.show()
```

---

## 11. 改进的TOPSIS方法

### 算法介绍

改进的TOPSIS方法针对传统TOPSIS的一些不足进行改进,如权重分配、距离度量、理想解确定等方面。

#### 11.1 基于博弈论的组合权重

**单一方法权重**:
- 熵权法权重:$w^{(1)}$
- AHP权重:$w^{(2)}$
- 变异系数法权重:$w^{(3)}$

**博弈论组合**:

优化问题:
$$
\min \| \sum_{k=1}^{L} \alpha_k w^{(k)} - w^{(k)} \|^2
$$

约束条件:$\sum_{k=1}^{L} \alpha_k = 1$,$\alpha_k \geq 0$

**最优解**:归一化$\alpha_k$得到组合权重$w = \sum_{k=1}^{L} \alpha_k w^{(k)}$

#### 11.2 改进的距离度量

**欧氏距离**(传统):
$$
D_i = \sqrt{\sum_{j=1}^{n} (v_{ij} - v_j^*)^2}
$$

**马氏距离**(考虑相关性):
$$
D_i = \sqrt{(v_i - v^*)^T \Sigma^{-1} (v_i - v^*)}
$$

其中$\Sigma$是协方差矩阵。

**加权切比雪夫距离**:
$$
D_i = \max_j \{ w_j |v_{ij} - v_j^*| \}
$$

#### 11.3 动态TOPSIS

**时序数据**:$X(t) = \{x_{ij}(t)\}$

**三维规范化**:
$$
r_{ij}(t) = \frac{x_{ij}(t)}{\sqrt{\sum_{t=1}^{T} \sum_{i=1}^{m} x_{ij}^2(t)}}
$$

**时序综合距离**:
$$
D_i^+ = \sqrt{\sum_{t=1}^{T} \sum_{j=1}^{n} [w_j(t) \cdot (v_{ij}(t) - v_j^+(t))]^2}
$$

#### 11.4 考虑决策者偏好的TOPSIS

**偏好系数**:$\lambda \in [0, 1]$

**修正贴近度**:
$$
C_i' = \lambda \cdot \frac{D_i^-}{D_i^+ + D_i^-} + (1 - \lambda) \cdot \frac{S_i}{S_{max}}
$$

其中$S_i$是方案的综合得分。

#### 11.5 基于前景理论的TOPSIS

**前景价值函数**:
$$
v(x) = \begin{cases}
x^\alpha, & x \geq 0 \\
-\theta(-x)^\beta, & x < 0
\end{cases}
$$

**权重函数**:
$$
\pi(p) = \frac{p^\gamma}{(p^\gamma + (1-p)^\gamma)^{1/\gamma}}
$$

**前景值**:$V = \sum_i \pi(p_i) v(x_i)$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 综合评价 | 复杂系统评价 | 需要组合权重 |
| 时序评价 | 多时期绩效评价 | 面板数据 |
| 行为决策 | 考虑心理偏好 | 非理性决策 |
| 相关性数据 | 指标相关性强 | 马氏距离 |
| 动态评价 | 发展变化评价 | 时序变化 |

### 可视化图表类型

- **权重对比图**:不同方法权重对比
- **时序演变图**:贴近度时序变化
- **敏感性分析图**:参数变化对排序影响
- **前景价值曲线**:价值函数曲线
- **三维TOPSIS图**:时序三维可视化

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Extension of TOPSIS for multi-objective large-scale nonlinear programming | Lai et al. | 1994 | Computers & Operations Research |
| A TOPSIS method with multiple forms of information | Yue | 2011 | Expert Systems with Applications |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import inv
from scipy.optimize import minimize

def game_theory_combination_weights(weight_list):
    """
    博弈论组合赋权
    :param weight_list: 多种方法的权重列表
    :return: 组合权重, 组合系数
    """
    n_methods = len(weight_list)
    n_criteria = weight_list[0].shape[0]

    W = np.column_stack(weight_list)  # (n_criteria, n_methods)

    # 构建优化问题
    def objective(alpha):
        w_combined = W @ alpha
        diff = W - w_combined.reshape(-1, 1)
        return np.sum(diff ** 2)

    # 约束条件
    constraints = {'type': 'eq', 'fun': lambda alpha: np.sum(alpha) - 1}
    bounds = [(0, None) for _ in range(n_methods)]
    initial_guess = np.ones(n_methods) / n_methods

    res = minimize(objective, initial_guess, method='SLSQP',
                  bounds=bounds, constraints=constraints)

    alpha_optimal = res.x
    w_combined = W @ alpha_optimal

    return w_combined, alpha_optimal

def topsis_mahalanobis(data, weights, directions=None):
    """
    基于马氏距离的TOPSIS
    :param data: 数据矩阵
    :param weights: 权重向量
    :param directions: 指标方向
    :return: 贴近度
    """
    data = np.array(data, dtype=float)
    weights = np.array(weights)
    m, n = data.shape

    if directions is None:
        directions = np.ones(n)

    # 标准化
    normalized = data / np.sqrt((data ** 2).sum(axis=0))
    weighted = normalized * weights

    # 计算协方差矩阵及其逆
    cov_matrix = np.cov(weighted.T)
    cov_inv = inv(cov_matrix + np.eye(n) * 1e-8)  # 添加正则化

    # 确定正负理想解
    v_positive = np.zeros(n)
    v_negative = np.zeros(n)

    for j in range(n):
        if directions[j] == 1:
            v_positive[j] = weighted[:, j].max()
            v_negative[j] = weighted[:, j].min()
        else:
            v_positive[j] = weighted[:, j].min()
            v_negative[j] = weighted[:, j].max()

    # 计算马氏距离
    d_positive = []
    d_negative = []

    for i in range(m):
        diff_p = weighted[i] - v_positive
        diff_n = weighted[i] - v_negative

        dist_p = np.sqrt(diff_p @ cov_inv @ diff_p)
        dist_n = np.sqrt(diff_n @ cov_inv @ diff_n)

        d_positive.append(max(0, dist_p))
        d_negative.append(max(0, dist_n))

    d_positive = np.array(d_positive)
    d_negative = np.array(d_negative)

    closeness = d_negative / (d_positive + d_negative + 1e-10)

    return closeness

def dynamic_topsis(data_3d, weights, directions=None):
    """
    动态TOPSIS(时序数据)
    :param data_3d: 三维数据 (n_samples, n_criteria, n_periods)
    :param weights: 权重向量或权重矩阵 (n_periods, n_criteria)
    :param directions: 指标方向
    :return: 各时期贴近度, 综合贴近度
    """
    data_3d = np.array(data_3d, dtype=float)
    n_samples, n_criteria, n_periods = data_3d.shape

    if directions is None:
        directions = np.ones(n_criteria)
    else:
        directions = np.array(directions)

    # 权重处理
    if np.array(weights).ndim == 1:
        weights = np.tile(weights, (n_periods, 1))

    # 三维规范化
    normalized = np.zeros_like(data_3d)
    for j in range(n_criteria):
        for t in range(n_periods):
            norm = np.sqrt(np.sum(data_3d[:, j, t] ** 2))
            if norm > 0:
                normalized[:, j, t] = data_3d[:, j, t] / norm

    # 各时期计算TOPSIS
    period_closeness = []

    for t in range(n_periods):
        data_t = normalized[:, :, t]
        weights_t = weights[t] if weights.ndim == 2 else weights

        weighted = data_t * weights_t

        # 正负理想解
        v_pos_t = np.zeros(n_criteria)
        v_neg_t = np.zeros(n_criteria)

        for j in range(n_criteria):
            if directions[j] == 1:
                v_pos_t[j] = weighted[:, j].max()
                v_neg_t[j] = weighted[:, j].min()
            else:
                v_pos_t[j] = weighted[:, j].min()
                v_neg_t[j] = weighted[:, j].max()

        # 距离
        d_pos = np.sqrt(((weighted - v_pos_t) ** 2).sum(axis=1))
        d_neg = np.sqrt(((weighted - v_neg_t) ** 2).sum(axis=1))

        closeness_t = d_neg / (d_pos + d_neg + 1e-10)
        period_closeness.append(closeness_t)

    period_closeness = np.column_stack(period_closeness)

    # 综合贴近度(简单平均)
    overall_closeness = period_closeness.mean(axis=1)

    return period_closeness, overall_closeness

def plot_dynamic_topsis(period_closeness, labels=None, title="Dynamic TOPSIS"):
    """绘制动态TOPSIS结果"""
    n_samples, n_periods = period_closeness.shape

    fig, ax = plt.subplots(figsize=(10, 6))

    x_pos = np.arange(n_periods)
    for i in range(n_samples):
        label = labels[i] if labels else f'Alternative {i+1}'
        ax.plot(x_pos, period_closeness[i], 'o-', label=label)

    ax.set_xlabel('Period')
    ax.set_ylabel('Closeness')
    ax.set_title(title)
    ax.set_xticks(x_pos)
    ax.set_xticklabels([f'T{t+1}' for t in range(n_periods)])
    ax.legend()
    plt.tight_layout()
    plt.show()

def prospect_topsis(data, weights, alpha=0.88, beta=0.88, theta=2.25, gamma=0.61):
    """
    基于前景理论的TOPSIS
    :param data: 数据矩阵
    :param weights: 权重向量
    :param alpha, beta, theta: 前景价值函数参数
    :param gamma: 权重函数参数
    :return: 前景贴近度
    """
    data = np.array(data, dtype=float)
    weights = np.array(weights)
    m, n = data.shape

    # 标准化
    normalized = data / np.sqrt((data ** 2).sum(axis=0))

    # 参考点(均值)
    reference = normalized.mean(axis=0)

    # 计算前景价值
    prospect_values = np.zeros((m, n))

    for i in range(m):
        for j in range(n):
            gain = normalized[i, j] - reference[j]
            if gain >= 0:
                prospect_values[i, j] = gain ** alpha
            else:
                prospect_values[i, j] = -theta * ((-gain) ** beta)

    # 计算前景贴近度
    gain_part = np.maximum(prospect_values, 0)
    loss_part = -np.minimum(prospect_values, 0)

    d_positive = np.sqrt(((weights * gain_part) ** 2).sum(axis=1))
    d_negative = np.sqrt(((weights * loss_part) ** 2).sum(axis=1))

    prospect_closeness = d_negative / (d_positive + d_negative + 1e-10)

    return prospect_closeness
```

---

## 12. 模糊综合评价 (Fuzzy Comprehensive Evaluation, FCE)

### 算法介绍

模糊综合评价基于模糊数学的隶属度理论,把定性评价转化为定量评价,处理"好/中/差"这类界限模糊的评价。适合指标多为定性、评语等级明确的评价问题,是国赛第二问(评价/排序类)高频方法。

#### 12.1 基本原理

**因素集与评语集**:
- 因素集 $U = \{u_1, u_2, \ldots, u_m\}$:参与评价的指标
- 评语集 $V = \{v_1, v_2, \ldots, v_n\}$:评价等级(如优/良/中/差)

**隶属度矩阵**:
$$
R = (r_{ij})_{m \times n}, \quad r_{ij} = \frac{\text{指标 } u_i \text{ 被评为 } v_j \text{ 的专家数}}{\text{专家总数}}
$$

**权重向量**:$W = (w_1, w_2, \ldots, w_m)$,可用 AHP/熵权法确定。

**综合评价**(加权平均型 $M(\cdot, \oplus)$,最常用):
$$
B = W \circ R, \quad b_j = \sum_{i=1}^{m} w_i r_{ij}
$$

**结果判定**:
- 最大隶属度原则:取 $\max_j b_j$ 对应等级
- 加权评分:给各等级赋分 $s_j$,得综合得分 $S = \sum_j b_j s_j$

#### 12.2 使用条件与常见坑

| 条件/坑 | 说明 | 应对 |
|---------|------|------|
| 权重需先确定 | FCE 不自动赋权 | 主观用 AHP,客观用熵权法,主客观结合更好 |
| 隶属度来源 | 定性指标靠专家打分,需样本 | 专家数不足时用隶属函数(如梯形/三角)构造 |
| 算子选择 | $M(\wedge, \vee)$ 会丢失信息 | 用加权平均型 $M(\cdot, \oplus)$ 保留全部信息 |
| 评语集粒度 | 等级太少区分度低、太多难打分 | 常用 3-5 级(优/良/中/差) |
| 归一化 | 权重需和为 1,隶属度每行和可为任意 | 权重归一化后再合成 |

#### 12.3 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 方案评价 | 选址、方案比选 | 定性指标多 |
| 质量评价 | 服务、环境质量 | 等级评语 |
| 风险评估 | 风险等级判定 | 模糊边界 |
| 绩效评价 | 综合评价排序 | 多指标 |

### 可视化图表类型

- **隶属度雷达图**:各方案各等级隶属度
- **综合得分条形图**:方案排序
- **权重饼图**:指标权重分布
- **评语分布图**:各指标评语占比

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Fuzzy sets | Zadeh | 1965 | Information and Control |
| 模糊数学及其应用 | 杨纶标、高英仪 | 2005 | 华南理工大学出版社 |

### 代码实现要点

```python
import numpy as np

def fuzzy_comprehensive_evaluation(weights, membership_matrix, grade_scores=None):
    """
    模糊综合评价(加权平均型)
    :param weights: 指标权重向量,和为 1,shape (m,)
    :param membership_matrix: 隶属度矩阵 shape (m, n),行=指标,列=评语等级
    :param grade_scores: 各等级赋分 shape (n,),用于加权评分(可选)
    :return: 综合评语向量 B, 等级(最大隶属度), 综合得分(可选)
    """
    weights = np.array(weights, dtype=float)
    R = np.array(membership_matrix, dtype=float)
    if not np.isclose(weights.sum(), 1.0, atol=1e-6):
        weights = weights / weights.sum()  # 权重归一化
    B = weights @ R  # 加权平均型合成
    grade = int(np.argmax(B))  # 最大隶属度
    score = None
    if grade_scores is not None:
        score = float(B @ np.array(grade_scores, dtype=float))
    return B, grade, score

def triangular_membership(x, a, b, c):
    """三角隶属函数(用于由数值指标构造隶属度)"""
    if x <= a or x >= c:
        return 0.0
    if x == b:
        return 1.0
    if a < x < b:
        return (x - a) / (b - a)
    return (c - x) / (c - b)

# 端到端示例:3 指标、4 等级(优/良/中/差)
if __name__ == '__main__':
    # 专家打分隶属度:指标1 有 6/10 专家评为优,等
    W = [0.4, 0.3, 0.3]  # 指标权重(如 AHP 得到)
    R = [
        [0.6, 0.3, 0.1, 0.0],  # 指标1
        [0.3, 0.5, 0.2, 0.0],  # 指标2
        [0.2, 0.4, 0.3, 0.1],  # 指标3
    ]
    grades = [95, 85, 70, 50]  # 各等级赋分
    B, grade, score = fuzzy_comprehensive_evaluation(W, R, grades)
    print(f"综合评语向量 B = {np.round(B, 3)}")
    print(f"最大隶属度等级 = {grade}(优=0/良=1/中=2/差=3)")
    print(f"综合得分 = {score:.2f}")
```

---

## 评价算法选择指南

### 按数据特征选择

| 数据特征 | 推荐算法 |
|---------|---------|
| 主观判断为主 | AHP、Fuzzy-AHP、主观赋权法 |
| 客观数据充分 | 熵权法、变异系数法、TOPSIS |
| 数据有明确优劣 | TOPSIS、秩和比法 |
| 样本量小(<10) | 灰色关联分析、AHP |
| 样本量大(>50) | 熵权法、TOPSIS、主成分分析 |
| 有模糊信息 | Fuzzy-AHP、模糊综合评价 |
| 需要完整排序 | TOPSIS、RSR、GRA |
| 只需要分类 | 聚类分析、RSR分档 |

### 按评价目的选择

| 评价目的 | 推荐算法 |
|---------|---------|
| 确定指标权重 | AHP、熵权法、变异系数法 |
| 方案排序 | TOPSIS、RSR、AHP+TOPSIS |
| 因素分析 | 灰色关联分析、主成分分析 |
| 综合评分 | 加权求和、TOPSIS、RSR |
| 分类分档 | RSR分档、聚类分析 |

### 按应用领域选择

| 应用领域 | 推荐算法 |
|---------|---------|
| 经济社会评价 | AHP、熵权法、TOPSIS |
| 工程技术评价 | AHP、模糊评价 |
| 环境质量评价 | 熵权法、TOPSIS |
| 卫生医疗评价 | RSR、TOPSIS |
| 教育质量评价 | AHP、灰色关联 |
| 风险评估 | AHP、模糊评价、灰色关联 |

### 组合方法推荐

| 组合方式 | 适用场景 |
|---------|---------|
| AHP + 熵权法 | 主客观结合赋权 |
| AHP + TOPSIS | 综合权重 + 方案排序 |
| 熵权法 + TOPSIS | 客观赋权 + 方案排序 |
| 熵权法 + 灰色关联 | 客观赋权 + 关联分析 |
| 模糊AHP + TOPSIS | 模糊评价 + 方案排序 |
| 熵权法 + 变异系数法 | 双重客观赋权验证 |

---

## 参考文献

1. Saaty, T. L. (1980). *The Analytic Hierarchy Process*. McGraw-Hill.
2. 邓聚龙. (1990). *灰色系统理论教程*. 华中理工大学出版社.
3. Hwang, C. L., & Yoon, K. (1981). *Multiple Attribute Decision Making: Methods and Applications*. Springer.
4. Zou, Z., Yun, Y., & Sun, J. (2006). Entropy method for determination of weight of evaluating indicators in fuzzy synthetic evaluation for water quality assessment. *Journal of Environmental Sciences*, 18(5), 1020-1023.
5. 田凤调. (1995). *秩和比法及其应用*. 中国卫生统计.
6. Van Laarhoven, P. J., & Pedrycz, W. (1983). A fuzzy extension of Saaty's priority theory. *Fuzzy Sets and Systems*, 11(1-3), 229-241.
7. Liu, S., & Lin, Y. (2006). *Grey Information: Theory and Practical Applications*. Springer.
8. Dalkey, N., & Helmer, O. (1963). An experimental application of the Delphi method to the use of experts. *Management Science*, 9(3), 458-467.
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall