[Mathematical Modeling] Analytic Hierarchy Process (AHP)-Python Implementation

1 Introduction

This article mainly explains the python implementation of the Analytic Hierarchy Process (AHP), and will follow up the example analysis later

2 code implementation

import package

import numpy as np

2.1 Construction of judgment matrix

The judgment matrix generally adopts the expert opinion method, that is, the Delphi method. However, there are no experts during the competition. You can just read it yourself. Of course, there are many articles that have improved the AHP, and you can refer to it yourself.
insert image description here
This article defines a 4*4 judgment matrix, that is, there are 4 indicators

A = np.array([[1,1/5,1/6,1/9],[5,1,1/2,1/6],[6,2,1,1/3],[9,6,3,1]])
print(A)

View the number of rows and columns of the matrix

#查看行数和列数
A.shape

insert image description here

2.2 Find eigenvalues ​​and eigenvectors

The method of solving eigenvalues ​​and eigenvectors mainly refers to the blog below

#求特征值和特征向量
'''
https://blog.csdn.net/Strive_For_Future/article/details/109631691
w,v = numpy.linalg.eig(a)  计算方形矩阵a的特征值和右特征向量
a : 待求特征值和特征向量的方阵。
w: 多个特征值组成的一个矢量。备注:多个特征值并没有按特定的次序排列。特征值中可能包含复数。
v: 多个特征向量组成的一个矩阵。每一个特征向量都被归一化了。第i列的特征向量v[:,i]对应第i个特征值w[i]。
'''
V,D = np.linalg.eig(A) # 求特征值和特征向量
print('特征值:')
print(V)
print('特征向量:')
print(D)

Output the largest eigenvalue and largest eigenvector, which is what we need

#最大特征值
tzz = np.max(V)
print('最大特征值为:\n', tzz)
#最大特征向量
k=[i for i in range(len(V)) if V[i] == np.max(V)]
tzx = -D[:,k]
print('最大特征值向量为:\n',tzx)

Get the weight Q, this Q is the weight matrix we need in the end, that is, the weight of each indicator

# 赋权重
n = A.shape[1]
quan=np.zeros((n,1))
for i in range(0,n):
    quan[i]=tzx[i]/np.sum(tzx)
Q=quan
print(Q)

insert image description here

2.3 Consistency check

This is to test whether our own judgment matrix is ​​reasonable. If the consistency test passes, it can be used. If it fails, it means that we have problems when scoring by experts, and we have to modify the judgment matrix.
insert image description here

#一致性检验
CI=(tzz-n)/(n-1)
RI=[0,0,0.58,0.9,1.12,1.24,1.32,1.41,1.45,1.49,1.52,1.54,1.56,1.58,1.59]
#判断是否通过一致性检验
CR=CI/RI[n-1]
if CR>=0.1:
    print('没有通过一致性检验, 判断矩阵需要进行修正\n')
else:
    print('通过一致性检验\n')

3 Example analysis

Suppose there are two objects with scores:
Object A: [8 7 6 8]
Object B: [7 8 8 7]

# 假设有两个目标
p = np.mat('8 7 6 8;7 8 8 7') #每一行代表一个对象的指标评分
print(p)

Then use the weight Q obtained above to score these two objects

#显示出所有评分对象的评分值
score=p*Q
for i in range(len(score)):
    print('object_score {}:'.format(i),float(score[i]))

insert image description here
It can be seen that the score of A is higher than that of B. You can try to define different judgment matrices to see the changes in the score.

Guess you like

Origin blog.csdn.net/qq_44319167/article/details/128824176