python层次分析法代码
时间: 2023-07-02 17:04:33 浏览: 368
以下是使用Python实现层次分析法的示例代码:
```python
import numpy as np
# 创建判断矩阵
def create_matrix(n):
matrix = np.zeros((n, n))
for i in range(n):
for j in range(n):
if i != j:
matrix[i][j] = 1 / float(input("请输入第%d个专家对第%d个指标的重要程度:" % (i+1, j+1)))
return matrix
# 计算权重向量
def calculate_weight(matrix):
n = len(matrix)
weight = np.zeros(n)
for i in range(n):
weight[i] = np.prod(matrix[i]) ** (1/float(n))
weight_sum = np.sum(weight)
weight = weight / weight_sum
return weight
# 计算一致性比率CR
def calculate_CR(matrix, weight):
n = len(matrix)
lambda_max = np.sum(np.dot(matrix, weight) / weight)
CI = (lambda_max - n) / (n - 1)
RI = [0, 0, 0.58, 0.90, 1.12, 1.24, 1.32, 1.41, 1.45, 1.49]
CR = CI / RI[n-1]
return CR
if __name__ == "__main__":
n = int(input("请输入指标个数:"))
matrix = create_matrix(n)
weight = calculate_weight(matrix)
CR = calculate_CR(matrix, weight)
if CR < 0.1:
print("一致性检验通过!")
print("权重向量为:", weight)
else:
print("一致性检验未通过,请重新输入!")
```
使用时,需要先输入指标个数,然后输入各个专家对各个指标的重要程度,最后输出计算得到的权重向量和一致性检验结果。若一致性检验通过,权重向量即为最终权重,反之需要重新输入。
阅读全文