Multi-Criteria Decision-Making Using AHP in Python

Sachin Last Updated : 13 Jun, 2023
8 min read

Introduction

In our daily lives, we make a lot of decisions based on a number of criteria. Some of these decisions are relatively unimportant, like deciding what to eat or wear. But some have a great impact, like the ones related to our career or professional work. When faced with a difficult decision, how do you consider every option to pick the best one? The Analytic Hierarchy Process (AHP) is one method you can use. It helps you make hard decisions by comparing multiple alternatives to make the best choice.

Learning Objectives:

  • Understand what the Analytical Hierarchy Process is.
  • Learn how to perform AHP in Python.

This article was published as a part of the Data Science Blogathon.

Understanding Analytical Hierarchy Process (AHP)

Let’s take a case of supply chain management. Imagine you are a procurement manager at ABC company and must choose the best supplier or vendor for your company’s raw materials. We may decide based on a single criterion like cost or maybe something else. Sometimes we make decisions by following our gut instincts or relying on past experiences. We may also seek others’ advice or list the pros and cons.

The decision-making process of selecting a supplier involves many criteria and evaluation factors. It is important to take into account both qualitative and quantitative factors at the same time to choose the best suppliers. Here, simply selecting the supplier with the lowest cost is not always a sensible choice. For instance, if the product is of low quality, it can cost more than the stated price. You should also consider delayed delivery. Giving other factors the necessary consideration to choose the supplier by focusing on its history, financial stability, and other factors may be the best course of action. So, a method that could help us process all the information and make our decision is called the analytic hierarchy process (AHP).

AHP is a multi-step decision analysis model that converts qualitative factors into quantitative measures. It uses linear algebra to calculate the importance of criteria using matrices. Giving weight to every criterion can make each criterion differ from another depending on its importance. The AHP approach uses this principle to evaluate alternatives.

How to Perform AHP?

Here are the steps to perform an AHP

  1. Identify the Objective, Criteria, and Alternatives

    Objective, Criteria, and Alternatives identification to streamline the process, maximize efficiency, and enhance decision outcomes.

  2. Create a Pair-wise Comparison Matrix of the Criteria Selected

    Construct a Pair-wise Comparison Matrix to facilitate AHP decision-making using selected criteria.

  3. Find the Priority Index for Each Attribute or Criterion

    Discover the Priority Index for AHP by Evaluating Attributes and Criteria, Ensuring Optimal Decision Making.

  4. Find the Consistency Ratio

    Discover the Consistency Ratio: A crucial measure for performing AHP effectively and achieving accurate decision-making.

  5. Find the Priority Index of the Suppliers Based on Each Criterion

    Utilize AHP to determine suppliers’ priority index by evaluating criteria and making informed decisions efficiently.

Step 1: Identify the Objective, Criteria, and Alternatives

Here our objective is supplier selection. There could be many criteria, but it is always possible to treat them as sub-criteria and group them into a limited number of major criteria. Here, 15 sub-criteria were identified for the four main criteria. We are assuming three different suppliers as alternatives.

Setting up the objective, criteria, and alternatives for Analytic Hierarchy Process (AHP) decision making process
Criteria matrix table for AHP

After deciding the decision framework, along with all the necessary criteria, we need to define a comparison scale that shows the verbal description of the relative importance between the two criteria in the form of a numerical rating.

Defining a comparison scale for AHP

Step 2: Create a Pair-wise Comparison Matrix of the Criteria Selected

This step builds a comparison matrix for each criteria pair based on the numerical rating scale defined in the last step. The selection of ratings is purely based on individual judgment and understanding. We can perform this step in Excel and directly add this matrix as a data frame in Python for further calculations.

Pair-wise comparison matrix of selected criteria | AHP decision-making process

A numerical rating of 3 between serviceability and supply capacity means that serviceability is moderately preferred oversupply capacity. Similarly, we can interpret each of the comparison ratings.

Step 3: Find the Priority Index for Each Attribute or Criterion

In this step, we perform a series of mathematical operations on the comparison matrix to calculate the priority index, which shows the relative importance of each criterion.

# Importing necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# Reading the file
ahp_df = pd.read_csv('pair_wise_comparison.csv')
ahp_df.set_index('Unnamed: 0', inplace=True)
ahp_df
Finding the priority index in Analytic Hierarchy Process
# We will introduce a function to find the priority index. 
# Then we provide the attributes data to this function.
def ahp_attributes(ahp_df):
    # Creating an array of sum of values in each column
    sum_array = np.array(ahp_df.sum(numeric_only=True))
    # Creating a normalized pairwise comparison matrix.
    # By dividing each column cell value with the sum of the respective column.
    cell_by_sum = ahp_df.div(sum_array,axis=1)
    # Creating Priority index by taking avg of each row
    priority_df = pd.DataFrame(cell_by_sum.mean(axis=1),
                               index=ahp_df.index,columns=['priority index'])
    priority_df = priority_df.transpose()
    return priority_df
# Calling the ahp_attributes function, 
# To return a table with the priority index for each attribute.
priority_index_attr = ahp_attributes(ahp_df)
priority_index_attr
Priority index for AHP

The output shows us that serviceability has the highest priority, followed by cost, and supply capacity has the least priority.

Step 4: Find the Consistency Ratio

The consistency ratio is a metric that defines whether the model based on our selection of criteria is consistent or not. We know that the model is consistent if the CR is less than 0.1. Now, we need to create a function to determine the consistency ratio. This function takes the priority index table for each attribute obtained from the previous step and the initial attributes table.

We will also introduce a random matrix. This matrix shows a constant value with respect to the length of our original attribute matrix. This value is finally used in calculating CR.

def consistency_ratio(priority_index,ahp_df):
    random_matrix = {1:0,2:0,3:0.58,4:0.9,5:1.12,6:1.24,7:1.32,
                     8:1.14,9:1.45,10:1.49,11:1.51,12:1.48,13:1.56,
                     14:1.57,15:1.59,16:1.605,17:1.61,18:1.615,19:1.62,20:1.625}
    # Check for consistency
    consistency_df = ahp_df.multiply(np.array(priority_index.loc['priority index']),axis=1)
    consistency_df['sum_of_col'] = consistency_df.sum(axis=1)
    # To find lambda max
    lambda_max_df = consistency_df['sum_of_col'].div(np.array(priority_index.transpose()
                                                              ['priority index']),axis=0)
    lambda_max = lambda_max_df.mean()
    # To find the consistency index
    consistency_index = round((lambda_max-len(ahp_df.index))/(len(ahp_df.index)-1),3)
    print(f'The Consistency Index is: {consistency_index}')
    # To find the consistency ratio
    consistency_ratio = round(consistency_index/random_matrix[len(ahp_df.index)],3)
    print(f'The Consistency Ratio is: {consistency_ratio}')
    if consistency_ratio<0.1:
        print('The model is consistent)
    else:
        print('The model is not consistent)
        
consistency_ratio(priority_index_attr,ahp_df)
Consistency index and consistency ratio in AHP

Since the consistency ratio is 0.069, i.e., less than 0.1, hence we can conclude that the consistency of the pairwise comparisons is considered reasonable, and the AHP process can be continued with further computations.

Step 5: Find the Priority Index of the Suppliers Based on Each Criterion

We will create a separate CSV file with each supplier’s weights or ratings w.r.t to the criteria. This matrix is a pairwise comparison of the supplier with the supplier under each criterion.

Pair-wise comparison for Analytic Hierarchy Process decision making process.

The above matrix shows that under the serviceability criterion, Supplier 2 is moderately preferred over Supplier 1, and similarly, we can interpret all other values. Again this matrix will develop using the same numerical scale mentioned above and involves individual judgment and understanding. Then we will import this matrix into Python and assign it a new data frame name.

ahp_df_1 = pd.read_csv('supplier-attribute.csv',header=[0], index_col=[0,1]) 
ahp_df_1
How AHP comparison and scoring works

We will define a new function for determining the supplier priority index and perform a series of mathematical operations.

def supplier_priority_index(suppl_attr_df,num_attr,attr_name):
    data_dict = {}
    # To find supplier priority indices
    # Supplier priority for attr 1
    data_dict[f"ahp_df_suppl_{attr_name}"] = suppl_attr_df.loc[attr_name]
    # Creating an array of sum of values in each column
    data_dict[f"sum_array_suppl_{attr_name}"] = np.array(data_dict[
        f"ahp_df_suppl_{attr_name}"].sum(numeric_only=True))
    # Normalised pairwise comparison matrix
    # Dividing each column cell value with the sum of the respective column.
    data_dict[f"norm_mat_suppl_{attr_name}"] = data_dict[
        f"ahp_df_suppl_{attr_name}"].div(data_dict[f"sum_array_suppl_{attr_name}"],axis=1)
    priority_df = pd.DataFrame(data_dict[
        f"norm_mat_suppl_{attr_name}"].mean(axis=1),
                               index=suppl_attr_df.loc[attr_name].index,columns=[attr_name])
    return priority_df
suppl_service_df = supplier_priority_index(ahp_df_1,4,'Serviceability')
suppl_capacity_df = supplier_priority_index(ahp_df_1,4,'Supply Capacity')
suppl_quality_df = supplier_priority_index(ahp_df_1,4,'Quality')
suppl_cost_df = supplier_priority_index(ahp_df_1,4,'Cost')

suppl_df = pd.concat([suppl_service_df,suppl_capacity_df,suppl_quality_df,suppl_cost_df],axis=1)
suppl_norm_df = suppl_df.multiply(np.array(priority_index_attr.loc['priority index']),axis=1)
suppl_norm_df['Sum'] = suppl_norm_df.sum(axis=1)
suppl_norm_df
Comparison and scoring in Analytic Hierarchy Process

From the above matrix, we need to choose the supplier with the maximum sum value of the ratings. As we can see from the above matrix, the sum of weights or ratings is the maximum for Supplier 2; hence it should be our choice of supplier to ensure optimal serviceability, supply capacity, quality, and cost.

Conclusion

In conclusion, the Analytic Hierarchy Process (AHP) can be a valuable tool to make decisions that are free from bias and ensures the decision reflects our values and priorities.

By breaking down the decision-making process into a hierarchy of criteria and sub-criteria, AHP allows decision-makers to evaluate the alternatives more objectively.

By using AHP, companies can also consider subjective factors such as the importance of various criteria and the preferences of different stakeholders. Overall, using AHP can help make more informed decisions, especially in the case of critical problems like selecting the best suppliers, leading to better outcomes in terms of quality, cost, and overall performance.

Key Takeaways

  • The Analytic Hierarchy Process is a multi-step decision analysis model that converts qualitative factors into quantitative measures.
  • AHP is a handy tool that helps machines make bias-free decisions and choose the best one from all available options.
  • We can implement AHP in 5 easy steps using Python.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Frequently Asked Questions

Q1. What is AHP and what is it used for?

A. AHP stands for Analytic Hierarchy Process. It is a decision-making method used to prioritize and make choices based on multiple criteria. AHP helps break down complex problems into a hierarchical structure and assigns relative weights to criteria to determine the best course of action.

Q2. What is the AHP method?

A. The AHP method is a decision-making technique that involves structuring a problem hierarchically, establishing criteria and alternatives, and pairwise comparing them based on their relative importance. Through a mathematical process, AHP computes priority weights for alternatives, aiding in informed decision-making.

Q3. What is an example of AHP analysis?

A. An example of AHP analysis is selecting the best location for a new business. Criteria such as cost, accessibility, market potential, and infrastructure are established. Alternatives like cities A, B, and C are compared pairwise based on these criteria, and AHP helps determine the most favorable location.

Q4. What scale is used in AHP?

A. AHP uses a numerical scale to capture the relative importance between criteria or alternatives. The most commonly used scale in AHP is a 1-9 scale, where 1 represents equal importance, 3 represents moderate pr

I am an MBA (Business Analytics) student. Highly enthusiastic about learning Machine learning and its use case across industries. I strongly believe in knowledge sharing and follow the same through my articles on Analytics Vidhya.

Responses From Readers

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details