改进AHP法特征项权重计算代码
时间: 2023-10-03 16:10:47 浏览: 50
AHP法特征项权重计算是一个比较复杂的过程,需要涉及到矩阵运算、特征值分解等数学知识。以下是一个可能的改进代码,主要是采用了numpy库进行矩阵运算,同时对代码进行了模块化设计,方便扩展和调试。
```python
import numpy as np
def normalize(matrix):
"""
对矩阵进行归一化处理
"""
col_sum = matrix.sum(axis=0)
norm_matrix = matrix / col_sum
return norm_matrix
def calc_weight(matrix):
"""
计算特征项权重
"""
num_criteria = matrix.shape[0] # 准则层数
num_items = matrix.shape[1] # 特征项数目
weights = np.zeros(num_items) # 权重向量
for i in range(num_criteria):
# 对每一层的矩阵进行归一化处理
norm_matrix = normalize(matrix[i,:,:])
# 计算准则层的权重向量
eig_val, eig_vec = np.linalg.eig(norm_matrix)
max_eig_val = eig_val.max()
eig_index = np.where(eig_val == max_eig_val)[0][0]
weights = weights + eig_vec[:,eig_index].real
# 归一化处理,使得权重向量的元素之和为1
weights = weights / sum(weights)
return weights
# 测试代码
if __name__ == '__main__':
# 构造一个3层的AHP矩阵,每层有4个特征项
ahp_matrix = np.array([
# 第1层矩阵
[[1, 3, 5, 7],
[1/3, 1, 3, 5],
[1/5, 1/3, 1, 3],
[1/7, 1/5, 1/3, 1]],
# 第2层矩阵
[[1, 3, 5, 7],
[1/3, 1, 3, 5],
[1/5, 1/3, 1, 3],
[1/7, 1/5, 1/3, 1]],
# 第3层矩阵
[[1, 3, 5, 7],
[1/3, 1, 3, 5],
[1/5, 1/3, 1, 3],
[1/7, 1/5, 1/3, 1]]
])
weights = calc_weight(ahp_matrix)
print(weights)
```
这段代码的主要改进在于使用了numpy库进行矩阵运算,可以大大简化代码的编写和优化运算速度。另外,代码还进行了模块化设计,方便扩展和调试。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)