close

紀錄一下最近的練習,雖然跟教授要我交的東西大有出路....

#AHP層級分析法演算法

雖然AHP已有Python 套件,但我看不懂^^,所以自己手做了一個

這個程式碼的範例可以參考底下的參考文獻(1),不過我認為此程式碼扔然存在缺陷,如下:

  • 如果Critical和Alternative具有很多項,那就得輸入很多次。

在這個範例中,critical本身n=5,我在輸入時就覺得很吃力了,有想過是否能用pd.read_csv之類的方式匯入,但目前沒想到這些比較項目在csv裡該如何表達。

  • 使用def沒辦法表達現在跑的特徵向量是屬於哪個critical的特徵向量

目前我還沒找到方法在 print('特徵向量 = ',step5)這行,有嘗試過{}.format但還沒寫出來。

# -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 17:10:06 2022

@author: user
"""
import numpy as np

RI_dict = {1:0, 2:0, 3:0.58, 4:0.9, 5:1.12, 6:1.24, 7:1.32, 8:1.41, 9:1.45}

#criteria的def
#step1: criteria 的成對矩陣
def pair_compare(n):
    A = np.ones([n,n])
    for i in range(0,n):
       for j in range(0,n):
          if (i<j):
             aij = input('criteria {} 比criteria {} 之重要程度為:'.format(i,j))
             A[i,j] = float(aij)
             A[j,i] = 1/float(aij)
    print('該criteria之成對矩陣 = ','\n',A)
        
    #step2: 成對矩陣直的相加
    step2 = np.round(np.sum(A,axis=0),3)
    # print('step2= ',step2)
    #step3: 原本成對矩陣/step2
    step3 = np.round(A/step2,3)
    # print('step3= ','\n',step3)
    #step4 step3橫的相加
    step4 = np.round(np.sum(step3,axis=1),3)
    # print('step4= ',step4)
    #step5 歸一化aka特徵向量
    step5 = np.round(step4/n,3)
    #dic1 = {0:'all_criteria' ,1:'品德' ,2:'才能' ,3:'資歷' ,4:'年齡' ,5:'群體關係'}
    print('{特徵向量 = ',step5)
    #計算CI CR step6
    nw = np.round(step5*n,3)
    AW = np.round((step5 *A).sum(axis=1),3)
    max_max = np.round(sum(AW / (nw)),3)
    CI =np.round((max_max-n)/(n-1),3)
    CR =np.round(CI/RI_dict[n],3)
    if CR <0.1:
        print('CR= ',CR,',可接受')
    else:
        print('CR= ',CR,',需重新計算')
        print('\n')
    return step5
p_c = pair_compare(5)#all_criteria
p_c_0 = pair_compare(3)#criteria0
p_c_1 = pair_compare(3)#criteria1
p_c_2 = pair_compare(3)#criteria2
p_c_3 = pair_compare(3)#criteria3
p_c_4 = pair_compare(3)#criteria4
print('\n')
alternative_p_c = np.round(p_c_0*p_c[0]+p_c_1*p_c[1]+p_c_2*p_c[2]+p_c_3*p_c[3]+p_c_4*p_c[4],3)
print('alternative的優先向量為 = ',alternative_p_c)
print('\n')

參考文獻

  1. https://www.cnblogs.com/yhll/p/9967726.html
  2. https://towardsdatascience.com/deep-dive-into-analytical-hierarchy-process-using-python-140385fabaa1

 

arrow
arrow
    文章標籤
    python AHP
    全站熱搜

    Ann 發表在 痞客邦 留言(0) 人氣()