# Analytic Hierarchy Process Model

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/analytic-hierarchy-process/>). I am continuously working to improve the translation.

**How can we bring the indicators to the same order of magnitude while ensuring that the differences under each indicator remain unchanged?**

Normalization: array [a, b, c] ->  $\frac{a}{a+b+c}, \frac{b}{a+b+c}, \frac{c}{a+b+c}$, then adjust their respective weights

## **Analytic Hierarchy Process (AHP)**:

### Model Principle:

Divide the problem into three levels: the top level (the goal), the middle level, and the bottom level (the alternatives provided for the decision)





### Basic Steps

#### 1. Build the hierarchical structure model

#### 2. Construct all the judgment matrices at each level

- Perform pairwise comparisons of the importance of the indicators to construct the **judgment matrix**, so as to derive the weights scientifically
- The meaning of $a_{ij}$ in the matrix: the importance of the $i$-th indicator relative to the $j$-th indicator

| Scale      | Meaning                                                                    |
| ---------- | -------------------------------------------------------------------------- |
| 1          | The two factors are equally important when compared                        |
| 3          | One factor is slightly more important than the other when compared         |
| 5          | One factor is clearly more important than the other when compared          |
| 7          | One factor is strongly more important than the other when compared         |
| 9          | One factor is extremely more important than the other when compared        |
| 2, 4, 6, 8 | Intermediate values of the two adjacent judgments above                    |

If we only ever compare two at a time, contradictions may arise in the end; in that case, a **consistency check** is needed

**Positive reciprocal matrix**: $a_{ij}>0 且 a_{ij} \times a_{ji}=1 且各行各列成比例$

**Consistent matrix**: if a positive reciprocal matrix satisfies $a_{ik} \times a_{kj}=a_{ij}$, then it is a consistent matrix

**Principle of the consistency check**: check whether the judgment matrix we constructed differs too much from a consistent matrix

<img src="C:\Users\endle\AppData\Roaming\Typora\typora-user-images\image-20250725113556672.png"  style="zoom: 33%;" />

#### 3. Compute the weights (to obtain the final weight vector)

Just apply the template)

- Geometric mean method for computing weights
- Arithmetic mean method for computing weights
- Eigenvalue method for computing weights



## AHP Python Code (AI)

```python
import numpy as np

class AHP:
    """
    使用 Python 实现层次分析法 AHP
    """

    def __init__(self, criteria, judgment_matrix):
        """
        初始化 AHP 类
        :param criteria: list, 评价准则的名称列表
        :param judgment_matrix: np.ndarray, 判断矩阵
        """
        self.criteria = criteria
        self.matrix = np.array(judgment_matrix)
        self.n = self.matrix.shape[0]

        # 随机一致性指标 RI 表
        self.RI = {
            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, 11: 1.51, 12: 1.48, 13: 1.56,
            14: 1.57, 15: 1.59
        }

    def _check_consistency(self, max_eigenvalue):
        """
        一致性检验
        公式：CR = CI / RI,  CI = (λ_max - n) / (n - 1)
        """
        CI = (max_eigenvalue - self.n) / (self.n - 1)

        # 当 n <= 2 时，判断矩阵总是一致的
        if self.n <= 2:
            CR = 0
        else:
            try:
                CR = CI / self.RI[self.n]
            except KeyError:
                print(f"警告：矩阵大小 n={self.n} 超出预设的 RI 表范围，无法计算 CR。")
                CR = float('nan')  # Not a Number

        print("\n--- 一致性检验 ---")
        print(f"最大特征值 λ_max = {max_eigenvalue:.4f}")
        print(f"一致性指标 CI = {CI:.4f}")
        if self.n > 2:
            print(f"随机一致性指标 RI = {self.RI.get(self.n, 'N/A')}")
            print(f"一致性比率 CR = {CR:.4f}")

        if CR < 0.10:
            print("结果：判断矩阵通过一致性检验。")
            return True
        else:
            print(f"结果：判断矩阵未通过一致性检验 (CR = {CR:.4f} >= 0.10)，建议修正判断矩阵。")
            return False

    def arithmetic_mean_method(self):
        """
        算术平均法求权重
        1. 将判断矩阵按列归一化
        2. 将归一化后的矩阵按行求和
        3. 将行和向量归一化得到权重向量
        """
        # 1. 按列归一化
        col_sum = np.sum(self.matrix, axis=0)
        normalized_matrix = self.matrix / col_sum

        # 2. 按行求和
        row_sum = np.sum(normalized_matrix, axis=1)

        # 3. 归一化得到权重
        weights = row_sum / self.n

        print("\n--- 1. 算术平均法 (Arithmetic Mean Method) ---")
        for i, w in enumerate(weights):
            print(f"  {self.criteria[i]:<10}: {w:.4f}")
        return weights

    def geometric_mean_method(self):
        """
        几何平均法求权重
        1. 计算判断矩阵每行元素的几何平均数
        2. 将得到的向量归一化
        """
        # 1. 计算每行乘积
        row_product = np.prod(self.matrix, axis=1)

        # 2. 计算 n 次方根
        root = np.power(row_product, 1 / self.n)

        # 3. 归一化得到权重
        weights = root / np.sum(root)

        print("\n--- 2. 几何平均法 (Geometric Mean Method) ---")
        for i, w in enumerate(weights):
            print(f"  {self.criteria[i]:<10}: {w:.4f}")
        return weights

    def eigenvalue_method(self):
        """
        特征值法求权重
        1. 求出判断矩阵的最大特征值及其对应的特征向量
        2. 对特征向量进行归一化处理
        """
        # 1. 计算特征值和特征向量
        eigenvalues, eigenvectors = np.linalg.eig(self.matrix)

        # 2. 找到最大特征值及其索引
        max_eigenvalue_index = np.argmax(eigenvalues)
        max_eigenvalue = np.real(eigenvalues[max_eigenvalue_index])

        # 3. 提取对应的特征向量
        eigenvector = np.real(eigenvectors[:, max_eigenvalue_index])

        # 4. 归一化权重向量
        weights = eigenvector / np.sum(eigenvector)

        print("\n--- 3. 特征值法 (Eigenvalue Method) ---")
        for i, w in enumerate(weights):
            print(f"  {self.criteria[i]:<10}: {w:.4f}")

        # 进行一致性检验
        self._check_consistency(max_eigenvalue)

        return weights, max_eigenvalue


if __name__ == '__main__':
    # --- 示例 ---
    # 假设需要选择一个旅游目的地，考虑四个准则：
    # C1: 景色
    # C2: 费用
    # C3: 交通
    # C4: 饮食
    criteria_names = ['景色', '费用', '交通', '饮食']

    # 构建判断矩阵 A
    # A[i, j] 表示准则 i 相对于准则 j 的重要性
    # 例如 A[0, 1] = 3 表示 "景色" 比 "费用" '稍重要'
    judgment_matrix = [
        [1, 3, 4, 2],
        [1 / 3, 1, 2, 1 / 2],
        [1 / 4, 1 / 2, 1, 1 / 3],
        [1 / 2, 2, 3, 1]
    ]

    # 实例化 AHP
    ahp_solver = AHP(criteria=criteria_names, judgment_matrix=judgment_matrix)

    # 分别使用三种方法计算权重
    w_arithmetic = ahp_solver.arithmetic_mean_method()
    w_geometric = ahp_solver.geometric_mean_method()
    # 特征值法会同时进行一致性检验
    w_eigen, lambda_max = ahp_solver.eigenvalue_method()

    print("\n--- 最终权重对比 ---")
    print(f"{'准则':<10} {'算术平均法':<12} {'几何平均法':<12} {'特征值法':<12}")
    print("-" * 50)
    for i in range(len(criteria_names)):
        print(f"{criteria_names[i]:<10} {w_arithmetic[i]:<12.4f} {w_geometric[i]:<12.4f} {w_eigen[i]:<12.4f}")
```
