<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rajiv Jarhad on Medium]]></title>
        <description><![CDATA[Stories by Rajiv Jarhad on Medium]]></description>
        <link>https://medium.com/@Rajiv_J?source=rss-7db0830f001c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jxBO9mixGHVZCLcxCcGHsA.jpeg</url>
            <title>Stories by Rajiv Jarhad on Medium</title>
            <link>https://medium.com/@Rajiv_J?source=rss-7db0830f001c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:46:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Rajiv_J/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Airline Fare Prediction using Machine Learning!!]]></title>
            <link>https://medium.com/@Rajiv_J/airline-fare-prediction-using-machine-learning-6d6922ffce1c?source=rss-7db0830f001c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6922ffce1c</guid>
            <dc:creator><![CDATA[Rajiv Jarhad]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 17:19:27 GMT</pubDate>
            <atom:updated>2024-12-05T03:40:03.139Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Aim of the Analysis</strong></blockquote><p>Airline fare prediction is one of the most complex and dynamic challenging problems in the world that involves finding the cost of flight tickets. This project mainly focuses on predicting airline fares using features such as airline class, Duration, Source, Destination, and other factors.</p><blockquote><strong>Relevance:</strong></blockquote><p>Air travel has become an integral part of modern life for both personal and professional purposes. However, ticket prices often fluctuate due to variables like seasonality, demand, and competition. These price variations create uncertainty for travellers, making it challenging to identify the optimal time to book flights. Developing a reliable airline fare prediction system will empower travellers to plan their journeys more effectively, minimize financial uncertainty, and make cost-conscious decisions.</p><blockquote><strong>Objectives:</strong></blockquote><ol><li>To develop a robust end-to-end machine-learning model following a complete Data Science project cycle, capable of accurately predicting airline fares based on historical and contextual data.</li><li>To identify and analyze the key factors influencing ticket prices, such as Airline, Airline class, booking time, travel season, airline, and travel class.</li><li>To process and transform user inputs into derived features, ensuring data consistency and accuracy for model prediction.</li><li>To implement an intuitive, user-friendly web interface that allows users to input basic flight details and receive real-time fare predictions.</li></ol><p>By doing this, the project aims to provide an understanding of the pricing trends and enable the users to make informed booking decisions.</p><blockquote><strong>Expected Outcomes:</strong></blockquote><ul><li><strong>Accurate Fare Prediction<br></strong>A trained machine learning model that delivers reliable and precise predictions for airline ticket prices.</li><li><strong>Understanding of Pricing Factors<br></strong>Insights into the underlying factors and trends affecting ticket prices, enabling users to make informed travel decisions.</li><li><strong>Professional Web Interface<br></strong>A clean, responsive, and user-friendly web application where users can effortlessly provide travel details and receive fare predictions.</li><li><strong>Improved Decision-Making for Travelers<br></strong>Travelers will benefit from reduced financial uncertainty and gain the ability to plan trips more cost-effectively.</li></ul><p><strong>Data Preparation: Loading Tools and Dataset</strong></p><blockquote><strong>Importing Required Libraries</strong></blockquote><pre># Importing necessary libraries<br>import pandas as pd  # For data manipulation and analysis<br>import numpy as np  # For numerical operations and handling missing values<br>import seaborn as sns  # For creating statistical visualizations<br>import matplotlib.pyplot as plt  # For plotting and visualization<br>from datetime import datetime  # For working with date and time objects<br>from google.protobuf.internal.well_known_types import Duration  </pre><blockquote><strong>Reading and Printing Dataset</strong></blockquote><pre># Reading the dataset from a CSV file into a Pandas DataFrame<br>df = pd.read_csv(&#39;Scraped_dataset.csv&#39;)<br><br># Displaying the first five rows of the DataFrame.<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4I_6GHBwTK1bmaZgziBEdg.png" /><figcaption><strong>First 5 rows of the Dataset</strong></figcaption></figure><p><strong>Handling Missing and Duplicate Data</strong></p><pre># Calculating the number of missing values in each column of the DataFrame<br>missing_values = df.isnull().sum()<br>print(&quot;Missing Values:&quot;)<br>print(missing_values)<br><br># Counting the number of duplicate rows in the DataFrame<br>duplicate_rows = df.duplicated().sum()<br>print(&quot;\nDuplicate Rows:&quot;, duplicate_rows)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*1TRTODYWSW7C2raFzUxleg.png" /><figcaption><strong>Count of Null and Duplicate Values</strong></figcaption></figure><blockquote><strong>Removing Duplicates and Finding shape of Data</strong></blockquote><pre># Removing duplicate rows from the DataFrame<br>df = df.drop_duplicates()<br><br># Displaying the shape of the DataFrame after removing duplicates (rows, columns)<br>print(df.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*zSTa4JgtRf3UB6d_UAf5eA.png" /><figcaption><strong>There are 445366 rows and 8 columns in the Dataset</strong></figcaption></figure><p><strong>Feature Extraction and Transformation</strong></p><blockquote><strong>Extracting Company, Flight Number, and Class from the ‘Airline-Class’ Column</strong></blockquote><pre># Function to extract specific information from a row containing multi-line text<br>def extract_info(row):<br>    lines = row.split(&#39;\n&#39;)  # Splitting the row content into separate lines<br>    if len(lines) &gt;= 3:<br>        # Returning the first three lines after stripping extra spaces<br>        return lines[0].strip(), lines[1].strip(), lines[2].strip()<br>    else:<br>        # Returning None for missing lines if the content has fewer than three lines<br>        return None, None, None<br><br># Applying the extract_info function to the &#39;Airline-Class&#39; column<br># and splitting the extracted data into three new columns: &#39;Company&#39;, &#39;FlightNumber&#39;, and &#39;Class&#39;<br>df[[&#39;Company&#39;, &#39;FlightNumber&#39;, &#39;Class&#39;]] = df[&#39;Airline-Class&#39;].apply(extract_info).apply(pd.Series)<br><br># Displaying the updated DataFrame with the new columns<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwgxBV3cXZ9Mqc0RoD43Hg.png" /><figcaption><strong><em>First 5 rows after extracting Company, Flight number and Class columns</em></strong></figcaption></figure><blockquote><strong>Cleaning the Price column: Removing “ , ”</strong></blockquote><pre># Function to clean and convert price values to integers<br>def clean_price(price):<br>    if isinstance(price, str):  # Checking if the price is a string<br>        # Removing commas and converting the string to an integer<br>        return int(price.replace(&#39;,&#39;, &#39;&#39;))<br>    else:<br>        # Returning the original value if it is not a string<br>        return price<br><br># Applying the clean_price function to the &#39;Price&#39; column to clean and format the data<br>df[&#39;Price&#39;] = df[&#39;Price&#39;].apply(clean_price)</pre><blockquote><strong>Extraction of Departure Time and Source from the Column “Departure Time”</strong></blockquote><pre># Function to extract departure time and source information from a row containing multi-line text<br>def extract_departure_info(row):<br>    lines = row.split(&#39;\n&#39;)  # Splitting the row content into separate lines<br>    if len(lines) &gt;= 2:<br>        # Returning the first two lines after stripping extra spaces<br>        return lines[0].strip(), lines[1].strip()<br>    else:<br>        # Returning None for missing lines if the content has fewer than two lines<br>        return None, None<br><br># Applying the extract_departure_info function to the &#39;Departure Time&#39; column<br># and splitting the extracted data into two new columns: &#39;DepartureTime&#39; and &#39;Source&#39;<br>df[[&#39;DepartureTime&#39;, &#39;Source&#39;]] = df[&#39;Departure Time&#39;].apply(extract_departure_info).apply(pd.Series)<br><br># Dropping the original &#39;Departure Time&#39; column as it has been processed into separate columns<br>df.drop(columns=[&#39;Departure Time&#39;], inplace=True)</pre><blockquote><strong>Extraction of Arrival Time and Destination from the Column “Arrival Time”</strong></blockquote><pre># Function to extract arrival time and destination information from a row containing multi-line text<br>def extract_arrival_info(row):<br>    lines = row.split(&#39;\n&#39;)  # Splitting the row content into separate lines<br>    if len(lines) &gt;= 2:<br>        # Returning the first two lines after stripping extra spaces<br>        return lines[0].strip(), lines[1].strip()<br>    else:<br>        # Returning None for missing lines if the content has fewer than two lines<br>        return None, None<br><br># Applying the extract_arrival_info function to the &#39;Arrival Time&#39; column<br># and splitting the extracted data into two new columns: &#39;ArrivalTime&#39; and &#39;Destination&#39;<br>df[[&#39;ArrivalTime&#39;, &#39;Destination&#39;]] = df[&#39;Arrival Time&#39;].apply(extract_arrival_info).apply(pd.Series)<br><br># Dropping the original &#39;Arrival Time&#39; column as it has been processed into separate columns<br>df.drop(columns=[&#39;Arrival Time&#39;], inplace=True)</pre><blockquote><strong>Converting the Total Stops Column to a numeric value.</strong></blockquote><pre># Mapping the &#39;Total Stops&#39; column values to numeric equivalents based on the &#39;stop_mapping&#39; dictionary<br>stop_mapping = {&#39;non-stop&#39;: 0, &#39;1-stop&#39;: 1, &#39;2-stop&#39;: 2}<br>df[&#39;Total Stops&#39;] = df[&#39;Total Stops&#39;].map(stop_mapping)<br><br># Displaying the unique values in the &#39;Total Stops&#39; column after applying the mapping<br>print(&quot;Unique values in &#39;Total Stops&#39; column after mapping:&quot;, df[&#39;Total Stops&#39;].unique())<br><br># Filling any missing values (NaN) in the &#39;Total Stops&#39; column with 0<br>df[&#39;Total Stops&#39;].fillna(0, inplace=True)<br><br># Displaying the unique values in the &#39;Total Stops&#39; column after filling NaN values<br>print(&quot;Unique values in &#39;Total Stops&#39; column after filling NaN values:&quot;, df[&#39;Total Stops&#39;].unique())<br><br># Displaying the data type of the &#39;Total Stops&#39; column after conversion<br>print(&quot;Data type of &#39;Total Stops&#39; column after conversion:&quot;, df[&#39;Total Stops&#39;].dtype)<br><br># Displaying the first few rows of the DataFrame to verify the changes<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOTNf1KFMukMgpjZsBYRsg.png" /><figcaption>First 5 rows after extracting new columns and transformations</figcaption></figure><blockquote><strong>Converting Duration to a Numeric value</strong></blockquote><pre>def convert_duration(duration):<br>    try:<br>        hours, minutes = duration.split(&#39;h &#39;)<br>        hours = int(hours)<br>        minutes = int(minutes[:-1])  # Remove &#39;m&#39; and convert to integer<br>        total_duration = hours + minutes / 60<br>        return total_duration<br>    except Exception as e:<br>        return np.nan<br><br># Apply duration conversion<br>data[&#39;Duration&#39;] = data[&#39;Duration&#39;].apply(convert_duration)</pre><blockquote><strong>Adding new Features : Day of Week_Jouney , Binary Indicator for Weekend, Booking Lead Time, Travel Season , Departure Hour , Arrival Hour, Binary Indicator for Class</strong></blockquote><pre># Extracting the day of the week from the &#39;Date of Booking&#39; and &#39;Date of Journey&#39; columns<br>df[&#39;DayOfWeek_Booking&#39;] = pd.to_datetime(df[&#39;Date of Booking&#39;]).dt.day_name()<br>df[&#39;DayOfWeek_Journey&#39;] = pd.to_datetime(df[&#39;Date of Journey&#39;]).dt.day_name()<br><br># Extracting the month from the &#39;Date of Journey&#39; column<br>df[&#39;Month_Journey&#39;] = pd.to_datetime(df[&#39;Date of Journey&#39;]).dt.month<br><br># Identifying if the journey date falls on a weekend (1 for weekend, 0 for weekday)<br>df[&#39;Weekend&#39;] = pd.to_datetime(df[&#39;Date of Journey&#39;]).dt.dayofweek // 5<br><br># Calculating the lead time in days between the booking date and the journey date<br>df[&#39;BookingLeadTime&#39;] = (pd.to_datetime(df[&#39;Date of Journey&#39;]) - pd.to_datetime(df[&#39;Date of Booking&#39;])).dt.days<br><br># Extracting the hour of departure and arrival from the respective columns<br>df[&#39;DepartureHour&#39;] = pd.to_datetime(df[&#39;DepartureTime&#39;]).dt.hour<br>df[&#39;ArrivalHour&#39;] = pd.to_datetime(df[&#39;ArrivalTime&#39;]).dt.hour<br><br># Creating binary indicators for the class type<br>df[&#39;IsEconomyClass&#39;] = df[&#39;Class&#39;].apply(lambda x: 1 if &#39;ECONOMY&#39; in x.upper() else 0)<br>df[&#39;IsBusinessClass&#39;] = df[&#39;Class&#39;].apply(lambda x: 1 if &#39;BUSINESS&#39; in x.upper() else 0)<br>df[&#39;IsFirstClass&#39;] = df[&#39;Class&#39;].apply(lambda x: 1 if &#39;FIRST&#39; in x.upper() else 0)<br><br># Function to determine the travel season based on the month<br>def get_travel_season(month):<br>    if month in [12, 1, 2]:  # Winter: December, January, February<br>        return &#39;Winter&#39;<br>    elif month in [3, 4, 5]:  # Spring: March, April, May<br>        return &#39;Spring&#39;<br>    elif month in [6, 7, 8]:  # Summer: June, July, August<br>        return &#39;Summer&#39;<br>    elif month in [9, 10, 11]:  # Autumn: September, October, November<br>        return &#39;Autumn&#39;<br>    else:<br>        return &#39;Unknown&#39;<br><br># Applying the travel season function to the &#39;Month_Journey&#39; column<br>df[&#39;TravelSeason&#39;] = df[&#39;Month_Journey&#39;].apply(get_travel_season)<br><br># Displaying the first few rows of the updated DataFrame<br>print(df.head())<br><br># Displaying all the column names in the DataFrame<br>print(df.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFfnsPwPIgAAzrC80i4-Mw.png" /><figcaption><strong>First 5 rows after creating new features</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0-yJdJELfKSzP-22iaQluQ.png" /><figcaption><strong>Columns in the dataset after creating new features</strong></figcaption></figure><blockquote>Creating column “Possible Routes” from Source to Destination</blockquote><pre>df[&#39;Possible Routes&#39;] = df[&#39;Source&#39;] + &#39; to &#39; + df[&#39;Destination&#39;]</pre><blockquote><strong>Finding the number of Unique Entries in Possible Routes</strong></blockquote><pre>num_unique_routes = df[&#39;Possible Routes&#39;].nunique()<br><br>print(&quot;Number of unique routes:&quot;, num_unique_routes)<br><br>unique_routes = df[&#39;Possible Routes&#39;].unique()<br><br>print(&quot;\nUnique routes:&quot;)<br>for route in unique_routes:<br>    print(route)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*joLbORXunQfoDM7cEhtFsQ.png" /><figcaption>There are a total of 42 unique routes.</figcaption></figure><blockquote><strong>Define a dictionary mapping possible routes to distances</strong></blockquote><pre>route_distances = {<br>    &#39;Delhi to Mumbai&#39;: 1140,<br>    &#39;Delhi to Bangalore&#39;: 1740,<br>    &#39;Delhi to Hyderabad&#39;: 1270,<br>    &#39;Delhi to Kolkata&#39;: 1310,<br>    &#39;Delhi to Chennai&#39;: 1770,<br>    &#39;Delhi to Ahmedabad&#39;: 775,<br>    &#39;Mumbai to Delhi&#39;: 1140,<br>    &#39;Mumbai to Bangalore&#39;: 840,<br>    &#39;Mumbai to Hyderabad&#39;: 620,<br>    &#39;Mumbai to Kolkata&#39;: 1720,<br>    &#39;Mumbai to Chennai&#39;: 1290,<br>    &#39;Mumbai to Ahmedabad&#39;: 440,<br>    &#39;Bangalore to Delhi&#39;: 1740,<br>    &#39;Bangalore to Mumbai&#39;: 840,<br>    &#39;Bangalore to Hyderabad&#39;: 500,<br>    &#39;Bangalore to Kolkata&#39;: 1740,<br>    &#39;Bangalore to Chennai&#39;: 290,<br>    &#39;Bangalore to Ahmedabad&#39;: 1200,<br>    &#39;Hyderabad to Delhi&#39;: 1270,<br>    &#39;Hyderabad to Mumbai&#39;: 620,<br>    &#39;Hyderabad to Bangalore&#39;: 500,<br>    &#39;Hyderabad to Kolkata&#39;: 1450,<br>    &#39;Hyderabad to Chennai&#39;: 525,<br>    &#39;Hyderabad to Ahmedabad&#39;: 940,<br>    &#39;Kolkata to Delhi&#39;: 1310,<br>    &#39;Kolkata to Mumbai&#39;: 1720,<br>    &#39;Kolkata to Bangalore&#39;: 1740,<br>    &#39;Kolkata to Hyderabad&#39;: 1450,<br>    &#39;Kolkata to Chennai&#39;: 1670,<br>    &#39;Kolkata to Ahmedabad&#39;: 1650,<br>    &#39;Chennai to Delhi&#39;: 1770,<br>    &#39;Chennai to Mumbai&#39;: 1290,<br>    &#39;Chennai to Bangalore&#39;: 290,<br>    &#39;Chennai to Hyderabad&#39;: 525,<br>    &#39;Chennai to Kolkata&#39;: 1670,<br>    &#39;Chennai to Ahmedabad&#39;: 1850,<br>    &#39;Ahmedabad to Delhi&#39;: 775,<br>    &#39;Ahmedabad to Mumbai&#39;: 440,<br>    &#39;Ahmedabad to Bangalore&#39;: 1200,<br>    &#39;Ahmedabad to Hyderabad&#39;: 940,<br>    &#39;Ahmedabad to Kolkata&#39;: 1650,<br>    &#39;Ahmedabad to Chennai&#39;: 1850<br>}<br><br>df[&#39;Distance&#39;] = df[&#39;Possible Routes&#39;].map(route_distances)</pre><blockquote><strong>Extracting “Departure_TimeOfDay” and “Arrival_TimeOfDay” from Departure Hour and Arrival Hour</strong></blockquote><pre># Define bins and labels<br>bins = [0, 6, 12, 18, 24]<br>labels = [&#39;Night&#39;, &#39;Morning&#39;, &#39;Afternoon&#39;, &#39;Evening&#39;]<br><br># Create Departure_TimeOfDay<br>df[&#39;Departure_TimeOfDay&#39;] = pd.cut(df[&#39;DepartureHour&#39;], bins=bins, labels=labels, right=False)<br><br># Create Arrival_TimeOfDay<br>df[&#39;Arrival_TimeOfDay&#39;] = pd.cut(df[&#39;ArrivalHour&#39;], bins=bins, labels=labels, right=False)<br><br># Display the resulting DataFrame<br>print(df.head())</pre><p><strong>Exploratory Data Analysis</strong></p><pre># Generating descriptive statistics for the DataFrame<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1qGtjmpxNU-OWTXUOmv2A.png" /></figure><pre># Displaying concise summary of the DataFrame, including the index dtype, column data types, and non-null values<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*Sh3dr0QTgqU297G4BFit5Q.png" /></figure><blockquote><strong>Saving the processed dataset into a new CSV file.</strong></blockquote><pre>df.to_csv(&quot;processed_airline_dataset.csv&quot;, index=False)</pre><p><strong>Data Visualisations</strong></p><pre># Importing the processed file.<br>data = pd.read_csv(&quot;processed_airline_dataset.csv&quot;)</pre><ol><li><strong><em>Plotting the number of bookings by Airline</em></strong></li></ol><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(10, 4))<br>sns.countplot(data=df, x=&#39;Company&#39;, hue=&#39;Company&#39;, dodge=False, palette=&#39;flare&#39;)  <br>plt.title(&#39;Number of Bookings by Airline&#39;, fontsize=16)  <br>plt.xlabel(&#39;Airline Company&#39;, fontsize=14)  <br>plt.ylabel(&#39;Number of Bookings&#39;, fontsize=14)<br>plt.xticks(rotation=45, ha=&#39;right&#39;, fontsize=12)  <br>plt.yticks(fontsize=12)  <br>plt.legend([], frameon=False) <br>plt.tight_layout()  <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*2MzwVDw2zflBWrV3NKk53w.png" /><figcaption><strong>Vistara leads the chart with the highest number of bookings, followed by Air India and Indigo, which are also among the most popular choices.</strong></figcaption></figure><p>2. <strong><em>Plotting Average price of flights by Airline</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(10, 6))<br>sns.boxplot(data=data, x=&#39;Company&#39;, y=&#39;Price&#39;)<br>plt.title(&#39;Average Price of Flights by Airline&#39;)<br>plt.xlabel(&#39;Airline&#39;)<br>plt.ylabel(&#39;Average Price&#39;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*L_R1UPDFKVFzu5fLaTAS7w.png" /><figcaption><strong>Vistara and Air India have the highest prices among all the airlines, while Indigo, SpiceJet, GoAir, and AirAsia offer relatively similar prices.<br> Interesting Insight: Despite having the highest prices, Vistara and Air India still maintain the highest number of bookings.</strong></figcaption></figure><p>3.<strong><em> Distribution of Flight Durations</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(12, 6))<br>sns.histplot(data=data, x=&#39;Duration&#39;, bins=range(0, 20, 2), kde=True, color=&#39;green&#39;)<br>plt.title(&#39;Distribution of Flight Durations&#39;, fontsize=16)  <br>plt.xlabel(&#39;Duration (hours)&#39;, fontsize=14)  <br>plt.ylabel(&#39;Frequency&#39;, fontsize=14)  <br>plt.xticks(fontsize=12)  <br>plt.yticks(fontsize=12)  <br>plt.xlim(0, 20)  <br>plt.grid(axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.7)  <br>plt.tight_layout()  <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfVB9pdInuY5CG61DZccMQ.png" /></figure><p>4. <strong><em>Average Price of Flights by Duration</em></strong></p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np<br><br># Define duration bins<br>duration_bins = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]<br><br>plt.figure(figsize=(12, 6))<br>sns.barplot(data=data, x=pd.cut(data[&#39;Duration&#39;], bins=duration_bins), y=&#39;Price&#39;, estimator=np.mean, ci=None)<br>plt.title(&#39;Average Price of Flights by Duration&#39;, fontsize=16)<br>plt.xlabel(&#39;Duration (hours)&#39;, fontsize=14)<br>plt.ylabel(&#39;Average Price&#39;, fontsize=14)<br>plt.xticks(rotation=45, fontsize=12)<br>plt.yticks(fontsize=12)<br>plt.grid(axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.5)<br>plt.ylim(0, 50000)  <br>plt.tight_layout()  <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpeIMBLxIyx7JElq5VeUqw.png" /><figcaption><strong>Price Increases as the duration of the flight Increases</strong></figcaption></figure><p>5. <strong><em>Count of Flights by Number of Stops</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>order = data[&#39;Total Stops&#39;].value_counts().index<br>plt.figure(figsize=(10, 6))<br>sns.countplot(data=data, x=&#39;Total Stops&#39;, order=order, color=&#39;skyblue&#39;)<br>plt.title(&#39;Count of Flights by Number of Stops&#39;, fontsize=16)<br>plt.xlabel(&#39;Number of Stops&#39;, fontsize=14)<br>plt.ylabel(&#39;Count of Flights&#39;, fontsize=14)<br>plt.xticks(fontsize=12)<br>plt.yticks(fontsize=12)<br>plt.tight_layout()  <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*213CrE4OuaZXJ9WKaTMc1Q.png" /><figcaption><strong>One-stop flights are more popular than direct flights</strong></figcaption></figure><p>6.<strong><em> Average Price of Flights by Number of Stops</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(8, 6))<br>sns.barplot(data=data, x=&#39;Total Stops&#39;, y=&#39;Price&#39;, order=order, color=&#39;green&#39;)<br>plt.title(&#39;Average Price of Flights by Number of Stops&#39;)<br>plt.xlabel(&#39;Number of Stops&#39;)<br>plt.ylabel(&#39;Average Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*NwHwNji6VOkd4A-PBAmyEQ.png" /><figcaption><strong>Direct flights have the lowest prices compared to flights with one or two stops.</strong></figcaption></figure><p>7. <strong><em>Count of Bookings by Season</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(8, 6))<br>sns.countplot(data=data, x=&#39;TravelSeason&#39;, color=&#39;orange&#39;)<br>plt.title(&#39;Count of Bookings by Season&#39;)<br>plt.xlabel(&#39;Travel Season&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*iNAJ8_hgfNuRrwgRj3aq6w.png" /></figure><p><strong><em>8. Plotting the relation between Departure Time and Arrival Time Vs Ticket Price</em></strong></p><pre>fig1 = px.box(data, x=&#39;DepartureHour&#39;, y=&#39;Price&#39;, color=&#39;Company&#39;, template=&#39;simple_white&#39;)<br>fig1.update_layout(title=&#39;Departure Time Vs Ticket Price&#39;, xaxis_title=&#39;DepartureHour&#39;, yaxis_title=&#39;Price&#39;)<br>fig1.show()<br><br>fig2 = px.box(data, x=&#39;ArrivalHour&#39;, y=&#39;Price&#39;, color=&#39;Company&#39;, template=&#39;simple_white&#39;)<br>fig2.update_layout(title=&#39;Arrival Time Vs Ticket Price&#39;, xaxis_title=&#39;ArrivalHour&#39;, yaxis_title=&#39;Price&#39;)<br>fig2.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTBLbB50Puf2No05OJVxsA.png" /><figcaption><strong>Flight prices vary depending on departure times. Night flights are generally the most expensive since airlines know some travellers prefer them for convenience or to maximize their time at their destination. Early morning, morning, and evening flights are usually priced similarly, catering to a wide range of travellers looking for a balance between cost and convenience. Late-night flights, however, are often the cheapest as airlines provide last-minute deals to fill empty seats on these less popular schedules.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_q5p7cmX8nPEGqp6Jssbsw.png" /><figcaption><strong>Arrival times also affect flight pricing. Evening flights are often the most expensive, especially for business travellers who want to arrive ready for meetings or work the next day. Morning and night flights are typically priced similarly. Morning arrivals are convenient for starting the day early, while night arrivals may be cheaper but less convenient. Late-night arrivals are usually the cheapest option, similar to late-night departures, as these times are less desirable for most travellers.</strong></figcaption></figure><p>9<strong><em>. Distribution of Departure Times</em></strong></p><pre>plt.figure(figsize=(10, 6))<br>sns.histplot(data=data, x=&#39;DepartureHour&#39;, kde=True)<br>plt.title(&#39;Distribution of Departure Times&#39;)<br>plt.xlabel(&#39;Hour of Departure&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*8GQNNpVWD5ri4xDHXAzZdw.png" /><figcaption><strong>Flight departure patterns show busy and quiet times during the day. The busiest hours, known as “rush hour in the sky,” are around 6 AM and 8 PM, with most flights taking off between 6 AM and 9 PM to meet traveller needs. Late nights (after 9 PM) and early mornings (before 6 AM) are much quieter, offering a calmer airport experience for those flying at these off-peak times.</strong></figcaption></figure><p>10. <strong><em>Distribution of Arrival Times</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(10, 6))<br>sns.histplot(data=data, x=&#39;ArrivalHour&#39;, kde=True, color=&#39;green&#39;)<br>plt.title(&#39;Distribution of Arrival Times&#39;)<br>plt.xlabel(&#39;Hour of Arrival&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*V8wlE6tuV28A_fj9Ea-SWA.png" /><figcaption><strong>Flight arrivals show distinct patterns throughout the day. Midday is the busiest period, with most flights landing between noon and 6 PM, peaking around 3 PM. Travellers during this time should expect crowded airports. Morning arrivals between 7 AM and noon are steady, providing a balance between avoiding peak congestion and early morning rushes. Late evenings and overnight hours are much quieter, with fewer arrivals between 1 AM and 4 AM. These times are ideal for travellers who prefer a more peaceful airport experience.</strong></figcaption></figure><p>11. <strong><em>Count of Bookings by Class</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(8, 6))<br>sns.countplot(data=data, x=&#39;Class&#39;, color =&#39;pink&#39;)<br>plt.title(&#39;Count of Bookings by Class&#39;)<br>plt.xlabel(&#39;Class&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*cod4yC_ew77RRt-MCG4BIw.png" /><figcaption><strong>Economy class dominates flight bookings, making it the most popular choice for travellers. Interestingly, business class surpasses premium economy in the number of bookings, highlighting a preference for added comfort and amenities. Meanwhile, first class remains the least booked option, catering to a smaller, niche audience.</strong></figcaption></figure><p>12.<strong><em> Percentage Distribution of Classes</em></strong></p><pre>class_counts = data[&#39;Class&#39;].value_counts()<br>class_counts_df = pd.DataFrame({&#39;Class&#39;: class_counts.index, &#39;Count&#39;: class_counts.values})<br>fig = px.pie(class_counts_df, values=&#39;Count&#39;, names=&#39;Class&#39;, hole=0.3)<br>fig.update_layout(title=&#39;Percentage Distribution of Classes&#39;, font=dict(size=12))<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z2dn4Zr1qdzeDneP83CWw.png" /></figure><p>13. <strong><em>Average Price of Flights by Class</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(8, 6))<br>sns.barplot(data=data, x=&#39;Class&#39;, y=&#39;Price&#39;, color = &#39;yellow&#39;)<br>plt.title(&#39;Average Price of Flights by Class&#39;)<br>plt.xlabel(&#39;Class&#39;)<br>plt.ylabel(&#39;Average Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*L3NHfRg0gs6dAHYHmVa4kg.png" /><figcaption><strong>As the cabin class becomes more premium, moving from Economy to Business to First, the prices increase significantly, reflecting the enhanced comfort, services, and exclusivity offered at each level.</strong></figcaption></figure><p>14.<strong><em> Plotting relation between Source City and Destination City Vs Ticket Price</em></strong></p><pre># Filter data based on price range<br>data_filtered = data[(data[&#39;Price&#39;] &gt;= 5000) &amp; (data[&#39;Price&#39;] &lt;= 100000)]<br>sns.set_style(&quot;whitegrid&quot;)<br><br># Box plot for Source City vs Ticket Price<br>plt.figure(figsize=(10, 6))  # Set the figure size<br>sns.boxplot(x=&#39;Source&#39;, y=&#39;Price&#39;, data=data_filtered, palette=&quot;flare&quot;)<br>plt.title(&#39;Source City Vs Ticket Price&#39;)<br>plt.xlabel(&#39;Source City&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.show()<br><br># Box plot for Destination City vs Ticket Price<br>plt.figure(figsize=(10, 6))  # Set the figure size<br>sns.boxplot(x=&#39;Destination&#39;, y=&#39;Price&#39;, data=data_filtered, palette=&quot;flare&quot;)<br>plt.title(&#39;Destination City Vs Ticket Price&#39;)<br>plt.xlabel(&#39;Destination City&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*Gc8xX9tEF1lCPrtpPu8Ajw.png" /><figcaption><strong>Cities with the highest average ticket prices include Delhi, which tops the list, followed by Mumbai and Bangalore. On the other hand, Kolkata offers the lowest average ticket prices, with Chennai and Ahmedabad close behind, making them more budget-friendly departure points.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*gWn_VT2l-glPbzaXa4Vngg.png" /><figcaption><strong>Flights to Kolkata and Chennai have the highest average ticket prices, making them the most expensive destinations. Mumbai and Bangalore have similar prices, falling in the middle range, neither the cheapest nor the most expensive. On the other hand, Delhi stands out as the most budget-friendly destination among the cities listed.</strong></figcaption></figure><p><strong><em>15. Count of Bookings by Route</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(24, 14))<br>sns.countplot(data=data, x=&#39;Possible Routes&#39;, color=&#39;skyblue&#39;)<br>plt.title(&#39;Count of Bookings by Route&#39;)<br>plt.xlabel(&#39;Route&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xmws7I0YdEJLIfvQvbcbZg.png" /><figcaption><strong>The busiest route, with the most flights and passengers, is between Delhi and Mumbai, while the least travelled route is from Kolkata to Ahmedabad. Other well-travelled routes include Delhi to Hyderabad, flights in both directions between Delhi and Mumbai, flights between Bangalore and Mumbai, and Bangalore to Delhi. These routes reflect the high demand and connectivity between major cities in India.</strong></figcaption></figure><p><strong><em>16. Average Price of Flights by Route</em></strong></p><pre># Set the seaborn style and color palette<br>sns.set_style(&quot;whitegrid&quot;)<br>colors = sns.color_palette(&quot;flare&quot;)<br># Create the bar plot<br>plt.figure(figsize=(26, 8))<br>sns.barplot(data=data, x=&#39;Possible Routes&#39;, y=&#39;Price&#39;, palette=colors)<br>plt.title(&#39;Average Price of Flights by Route&#39;, fontsize=16)<br>plt.xlabel(&#39;Route&#39;, fontsize=14)<br>plt.ylabel(&#39;Average Price&#39;, fontsize=14)<br>plt.xticks(rotation=45, fontsize=12)<br>plt.yticks(fontsize=12)<br>plt.tight_layout() <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPT6HdfXA5AV3NWMM732QA.png" /><figcaption><strong>The most expensive route is from Kolkata (CCU) to Ahmedabad (AMD). Flights departing from Delhi (DEL) are generally cheaper than those from other cities, especially on routes like DEL to Mumbai (BOM), DEL to Hyderabad (HYD), and DEL to Bangalore (BLR). Flights between major cities in South India, including Bangalore (BLR), Hyderabad (HYD), Chennai (MAA), and Kolkata (CCU), have a similar price range, indicating consistent pricing within this region.</strong></figcaption></figure><p>17<strong><em>. Plotting Booking Trends by Day of the Week and Weekend (Journey)</em></strong></p><pre>sns.set_style(&quot;whitegrid&quot;)<br>colors = sns.color_palette(&quot;flare&quot;)<br><br>plt.figure(figsize=(10, 6))<br>sns.countplot(data=df, x=&#39;DayOfWeek_Journey&#39;, palette=&#39;pastel&#39;)<br>plt.title(&#39;Count of Bookings by Day of the Week (Journey)&#39;)<br>plt.xlabel(&#39;Day of the Week&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.show()<br><br><br>plt.figure(figsize=(10, 6))<br>sns.countplot(data=df, x=&#39;Weekend&#39;,palette=&#39;pastel&#39;)<br>plt.title(&#39;Count of Bookings by Weekend (Journey)&#39;)<br>plt.xlabel(&#39;weekend&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.show()<br><br><br>plt.figure(figsize=(10, 6))<br>sns.countplot(data=df, x=&#39;Month_Journey&#39;,palette=&#39;pastel&#39;)<br>plt.title(&#39;Count of Bookings by Day of the Week (Journey)&#39;)<br>plt.xlabel(&#39;Month_Journey&#39;)<br>plt.ylabel(&#39;Count of Bookings&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*bjSguIgJzlGscOY6yk1uAw.png" /><figcaption><strong>Even though the number of bookings stays fairly consistent throughout the week, Mondays see the most flights booked for the actual travel day.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*9fjET2Qe4NlXMkEulZ0s5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*pde5HlhlTuqMr8kl8eY5-A.png" /></figure><p><strong><em>18. Plotting Price Distribution Based on Journey Day and Weekend</em></strong></p><pre>plt.figure(figsize=(10, 6))<br>sns.lineplot(data=df, x=&#39;DayOfWeek_Journey&#39;, y=&#39;Price&#39;, color=&#39;skyblue&#39;)<br>plt.title(&#39;Price Distribution by Day of the Week (Journey)&#39;)<br>plt.xlabel(&#39;Day of the Week&#39;)<br>plt.ylabel(&#39;Average Price&#39;)<br>plt.show()<br><br>plt.figure(figsize=(6, 6))<br>sns.lineplot(data=df, x=&#39;Weekend&#39;, y=&#39;Price&#39;, color=&#39;lightgreen&#39;)<br>plt.title(&#39;Price Distribution of Bookings by Weekend (Journey)&#39;)<br>plt.xlabel(&#39;Weekend&#39;)<br>plt.ylabel(&#39;Average Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*4HXypTAPeehv_yL-8RwHyQ.png" /><figcaption><strong>Flight prices are generally higher at the beginning of the week, on Mondays and Tuesdays. Prices then tend to decrease throughout the week, reaching a low point on Thursdays and then tending to rise on Saturdays and Sundays.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*Li36ARmsjzcWfBmZUWcPzg.png" /></figure><p>19. <strong><em>Plotting Booking Lead Time and Ticket Price Analysis</em></strong></p><pre>plt.figure(figsize=(16, 6))<br>sns.countplot(data=df, x=&#39;BookingLeadTime&#39;)<br>plt.title(&#39;Distribution of Booking Lead Time&#39;)<br>plt.xlabel(&#39;Booking Lead Time&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()<br><br><br><br>plt.figure(figsize=(10,6))<br>sns.lineplot(data=df,x=&#39;BookingLeadTime&#39;,y=&#39;Price&#39;,color=&#39;red&#39;)<br>plt.title(&#39;Booking Lead Time Versus Ticket Price&#39;)<br>plt.xlabel(&#39;Booking Lead Time for Departure&#39;)<br>plt.ylabel(&#39;Price&#39;,)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQPWo_fQVGZjg6iV-1_x3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*T3dZQUZ_h79MTI6YwSZpMg.png" /><figcaption><strong>People book flights consistently throughout the booking window, with no significant difference in bookings on specific days. However, the highest number of bookings occurs around 15 days before departure. As the departure date gets closer (within 2 days), the number of bookings decreases. This trend is also reflected in ticket prices, which tend to rise as the departure date nears due to limited seat availability. Booking around 15 days before departure may offer a better deal.</strong></figcaption></figure><p>20. <strong><em>Plotting Flight Distances and Pricing Insights</em></strong></p><pre>plt.figure(figsize=(16, 6))<br>sns.countplot(data=df, x=&#39;Distance&#39;, color=&#39;skyblue&#39;)<br>plt.title(&#39;Distribution of Flight Distances&#39;)<br>plt.xlabel(&#39;Distance&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()<br><br>data_filtered = data[(data[&#39;Price&#39;] &gt;= 5000) &amp; (data[&#39;Price&#39;] &lt;= 100000)]<br><br>plt.figure(figsize=(12, 6))<br>sns.lineplot(data=df, x=&#39;Distance&#39;, y=&#39;Price&#39;, color=&#39;green&#39;)<br>plt.title(&#39;Flight Distances vs. Price&#39;)<br>plt.xlabel(&#39;Distance&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52-C7TkMitbUvyPODn4bLQ.png" /><figcaption><strong>There is a significant number of flights across all distance ranges, indicating a mix of short-haul, medium-haul, and long-haul flights. However, the number of flights gradually decreases as the distance increases, meaning there are fewer flights between airports that are farther apart.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*WTgkFed2kRxV4B0dWiwW1g.png" /><figcaption><strong>Some short flights are more expensive than certain long flights, which can be due to factors like high demand or limited competition on specific routes, differences in airline pricing, or peak travel seasons. On the other hand, some long flights are cheaper than short ones, possibly due to special offers, discounts, or strong competition on particular long routes. These variations show how different factors can influence flight prices regardless of the distance.</strong></figcaption></figure><p><strong>Preparing Data for Model Training</strong></p><blockquote><strong>Importing Required Libraries for Model Training</strong></blockquote><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import OneHotEncoder, StandardScaler<br>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.ensemble import GradientBoostingRegressor<br>from sklearn.metrics import mean_squared_error, r2_score<br>import joblib<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.linear_model import LinearRegression<br>from sklearn.svm import SVR<br>from sklearn.neighbors import KNeighborsRegressor<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.ensemble import AdaBoostRegressor</pre><pre>#Dropping the &quot;Airline-Class&quot; column as its information has been extracted<br>data.drop(columns=&quot;Airline-Class&quot;, inplace=True)</pre><pre># Renaming the &quot;Company&quot; column to &quot;Airline&quot; for better clarity and alignment with the dataset&#39;s context<br>data.rename(columns={&#39;Company&#39;: &#39;Airline&#39;}, inplace=True)</pre><blockquote><strong>Defining the required Columns</strong></blockquote><pre># Define the columns to keep<br>columns_to_keep = [<br>    &#39;Total Stops&#39;, &#39;Airline&#39;, &#39;Source&#39;, &#39;Destination&#39;, &#39;DayOfWeek_Journey&#39;,<br>    &#39;Month_Journey&#39;, &#39;Weekend&#39;, &#39;BookingLeadTime&#39;, &#39;DepartureHour&#39;, &#39;ArrivalHour&#39;,<br>    &#39;IsEconomyClass&#39;, &#39;IsBusinessClass&#39;, &#39;IsFirstClass&#39;, &#39;TravelSeason&#39;, &#39;Distance&#39;<br>]<br>data = data[columns_to_keep + [&#39;Price&#39;]</pre><blockquote><strong>Modifying required Data types</strong></blockquote><pre># Feature Engineering<br>data[&#39;DayOfWeek_Journey&#39;] = pd.to_datetime(data[&#39;Date of Journey&#39;]).dt.day_name()<br>data[&#39;Month_Journey&#39;] = pd.to_datetime(data[&#39;Date of Journey&#39;]).dt.month<br>data[&#39;Weekend&#39;] = pd.to_datetime(data[&#39;Date of Journey&#39;]).dt.dayofweek // 5<br>data[&#39;BookingLeadTime&#39;] = (pd.to_datetime(data[&#39;Date of Journey&#39;]) - pd.to_datetime(data[&#39;Date of Booking&#39;])).dt.days<br>data[&#39;DepartureHour&#39;] = pd.to_datetime(data[&#39;DepartureTime&#39;]).dt.hour<br>data[&#39;ArrivalHour&#39;] = pd.to_datetime(data[&#39;ArrivalTime&#39;]).dt.hour<br>data[&#39;IsEconomyClass&#39;] = data[&#39;Class&#39;].apply(lambda x: 1 if &#39;ECONOMY&#39; in x.upper() else 0)<br>data[&#39;IsBusinessClass&#39;] = data[&#39;Class&#39;].apply(lambda x: 1 if &#39;BUSINESS&#39; in x.upper() else 0)<br>data[&#39;IsFirstClass&#39;] = data[&#39;Class&#39;].apply(lambda x: 1 if &#39;FIRST&#39; in x.upper() else 0)</pre><blockquote><strong>Saving the processed dataset into Final CSV file.</strong></blockquote><pre>data.to_csv(&quot;Final_data.csv&quot;, index=False)</pre><blockquote><strong>Importing Final Data for Training Models</strong></blockquote><pre># Load the data<br>data = pd.read_csv(&#39;Final_data.csv&#39;)</pre><blockquote><strong>Getting Info about Final Data.</strong></blockquote><pre>data.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*1v31ZTxFJWqTwRdXoxM3zw.png" /></figure><blockquote><strong>Define features and target</strong></blockquote><pre>X = data.drop(columns=&#39;Price&#39;)<br>y = data[&#39;Price&#39;]</pre><blockquote><strong>Define categorical and numerical columns</strong></blockquote><pre>categorical_cols = X.select_dtypes(include=[&#39;object&#39;]).columns<br>numerical_cols = X.select_dtypes(include=[&#39;number&#39;]).columns</pre><blockquote><strong>Preprocessing for numerical data</strong></blockquote><pre>numerical_transformer = Pipeline(steps=[<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;median&#39;)),(&#39;scaler&#39;, StandardScaler())])</pre><blockquote><strong>Preprocessing for categorical data</strong></blockquote><pre>categorical_transformer = Pipeline(steps=[<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;most_frequent&#39;)),<br>    (&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))])</pre><blockquote><strong>Bundle preprocessing for numerical and categorical data</strong></blockquote><pre>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&#39;num&#39;, numerical_transformer, numerical_cols),<br>        (&#39;cat&#39;, categorical_transformer, categorical_cols)])</pre><p><strong>Training Machine Learning Models</strong></p><blockquote><strong>Training Models using Laaso and Ridge regression and testing their performance</strong></blockquote><pre>from sklearn.linear_model import Lasso, Ridge<br>from sklearn.pipeline import Pipeline<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error, r2_score<br><br># Split the data into training, validation, and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=42)<br><br># Define the models<br>models = {<br>    &#39;Lasso&#39;: Lasso(),<br>    &#39;Ridge&#39;: Ridge()}<br><br>results = {}<br>for name, model in models.items():<br>    model_pipeline = Pipeline(steps=[<br>        (&#39;preprocessor&#39;, preprocessor),<br>        (&#39;model&#39;, model)])<br>    model_pipeline.fit(X_train, y_train)<br>    val_predictions = model_pipeline.predict(X_val)<br>    test_predictions = model_pipeline.predict(X_test)<br>    val_rmse = mean_squared_error(y_val, val_predictions, squared=False)<br>    val_r2 = r2_score(y_val, val_predictions)<br>    test_rmse = mean_squared_error(y_test, test_predictions, squared=False)<br>    test_r2 = r2_score(y_test, test_predictions)<br>    results[name] = {<br>        &#39;Validation&#39;: {&#39;RMSE&#39;: val_rmse, &#39;R2&#39;: val_r2},<br>        &#39;Test&#39;: {&#39;RMSE&#39;: test_rmse, &#39;R2&#39;: test_r2}}</pre><blockquote><strong>Result of Ridge and Lasso Regression</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*6m3CEcO4r_XqkJJenGSgOQ.png" /></figure><blockquote><strong>Performing hyperparameter tuning for Lasso and Ridge regression using grid search</strong></blockquote><pre>from sklearn.model_selection import GridSearchCV<br><br># Defining the models<br>models = {<br>    &#39;Lasso&#39;: Lasso(),<br>    &#39;Ridge&#39;: Ridge()}<br># Defining the hyperparameters<br>params = {<br>    &#39;Lasso&#39;: {&#39;model__alpha&#39;: [0.1, 0.5, 1.0, 2.0, 5.0]},<br>    &#39;Ridge&#39;: {&#39;model__alpha&#39;: [0.1, 0.5, 1.0, 2.0, 5.0]}<br>}<br><br>results = {}<br>for name, model in models.items():<br>    model_pipeline = Pipeline(steps=[<br>        (&#39;preprocessor&#39;, preprocessor),<br>        (&#39;model&#39;, model)])<br>    grid_search = GridSearchCV(model_pipeline, params[name], cv=3, scoring=&#39;neg_root_mean_squared_error&#39;)<br>    grid_search.fit(X_train, y_train)<br>    val_predictions = grid_search.predict(X_val)<br>    test_predictions = grid_search.predict(X_test)<br>    val_rmse = mean_squared_error(y_val, val_predictions, squared=False)<br>    val_r2 = r2_score(y_val, val_predictions)<br>    test_rmse = mean_squared_error(y_test, test_predictions, squared=False)<br>    test_r2 = r2_score(y_test, test_predictions)<br>    results[name] = {<br>        &#39;Validation&#39;: {&#39;RMSE&#39;: val_rmse, &#39;R2&#39;: val_r2},<br>        &#39;Test&#39;: {&#39;RMSE&#39;: test_rmse, &#39;R2&#39;: test_r2},<br>        &#39;Best_Params&#39;: grid_search.best_params_}<br>    <br>results_df = pd.DataFrame(results).T<br>print(results_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*5aDBsqng39umZYLjrFlzjQ.png" /><figcaption><strong>Result of Hyperparameter Tuning for Ridge and Lasso Regression</strong></figcaption></figure><blockquote><strong>Training Model using KNN Regressor and Decision Tree Regressor</strong></blockquote><pre>from sklearn.neighbors import KNeighborsRegressor<br>from sklearn.tree import DecisionTreeRegressor<br><br># Defining the models<br>models = {<br>    &#39;KNN&#39;: KNeighborsRegressor(),<br>    &#39;DecisionTree&#39;: DecisionTreeRegressor()}<br>results = {}<br>for name, model in models.items():<br>    model_pipeline = Pipeline(steps=[<br>        (&#39;preprocessor&#39;, preprocessor),<br>        (&#39;model&#39;, model)])<br>    model_pipeline.fit(X_train, y_train)<br>    val_predictions = model_pipeline.predict(X_val)<br>    test_predictions = model_pipeline.predict(X_test)<br>    val_rmse = mean_squared_error(y_val, val_predictions, squared=False)<br>    val_r2 = r2_score(y_val, val_predictions)<br>    test_rmse = mean_squared_error(y_test, test_predictions, squared=False)<br>    test_r2 = r2_score(y_test, test_predictions)<br>    results[name] = {<br>        &#39;Validation&#39;: {&#39;RMSE&#39;: val_rmse, &#39;R2&#39;: val_r2},<br>        &#39;Test&#39;: {&#39;RMSE&#39;: test_rmse, &#39;R2&#39;: test_r2}}<br>    <br>results_df = pd.DataFrame(results).T<br>print(results_df)</pre><blockquote><strong>Result of KNN and Decision Tree</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*QjjOX5VfBVe5rQAxjpYrIA.png" /><figcaption><strong>The KNN model performed well in capturing simpler patterns but struggled with high-dimensional data due to its reliance on local neighbours. Increasing the value of k reduced overfitting by considering more neighbours, but it also diminished the model’s ability to detect finer variations. The Decision Tree model effectively captured non-linear relationships, explaining a significant portion of ticket price variation. However, its tendency to overfit by memorising training data reduced its ability to generalise to unseen data.</strong></figcaption></figure><blockquote><strong>Performing hyperparameter tuning for KNN and Decision tree using grid search</strong></blockquote><pre>from sklearn.model_selection import GridSearchCV<br># Defining the models<br>models = {<br>    &#39;KNN&#39;: KNeighborsRegressor(),<br>    &#39;DecisionTree&#39;: DecisionTreeRegressor()}<br># Defining the hyperparameters<br>params = {<br>    &#39;KNN&#39;: {&#39;model__n_neighbors&#39;: [3, 5, 7, 9, 11]},<br>    &#39;DecisionTree&#39;: {&#39;model__max_depth&#39;: [3, 5, 7, 9, 11]}<br>}<br><br>results = {}<br>for name, model in models.items():<br>    model_pipeline = Pipeline(steps=[<br>        (&#39;preprocessor&#39;, preprocessor),<br>        (&#39;model&#39;, model)])<br>    grid_search = GridSearchCV(model_pipeline, params[name], cv=3, scoring=&#39;neg_root_mean_squared_error&#39;)<br>    grid_search.fit(X_train, y_train)<br>    val_predictions = grid_search.predict(X_val)<br>    test_predictions = grid_search.predict(X_test)<br>    val_rmse = mean_squared_error(y_val, val_predictions, squared=False)<br>    val_r2 = r2_score(y_val, val_predictions)<br>    test_rmse = mean_squared_error(y_test, test_predictions, squared=False)<br>    test_r2 = r2_score(y_test, test_predictions)<br>    results[name] = {<br>        &#39;Validation&#39;: {&#39;RMSE&#39;: val_rmse, &#39;R2&#39;: val_r2},<br>        &#39;Test&#39;: {&#39;RMSE&#39;: test_rmse, &#39;R2&#39;: test_r2},<br>        &#39;Best_Params&#39;: grid_search.best_params_}<br>    <br>results_df = pd.DataFrame(results).T<br>print(results_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Bkiw3AlODv2DHf9DrSGoIA.png" /><figcaption><strong>Hyperparameter tuning was carried out using grid search with 3-fold cross-validation to improve model performance and the explained variation (R²). For the KNN Regressor, the optimal number of neighbors was identified as 7, striking a balance between generalization and overfitting. For the Decision Tree Regressor, the best maximum depth was found to be 11, enhancing the model’s ability to generalize to unseen data while explaining a significant proportion of variation in ticket prices.</strong></figcaption></figure><blockquote><strong>Training Model using XGBoost Regressor</strong></blockquote><pre>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br>import xgboost as xgb<br>from sklearn.pipeline import Pipeline<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error, r2_score<br><br># Define the XGBoost model with GPU support<br>model = xgb.XGBRegressor(n_estimators=2000,<br>                         learning_rate=0.01,<br>                         max_depth=10,<br>                         subsample=0.8,<br>                         random_state=42,<br>                         tree_method=&#39;gpu_hist&#39;,  # Use GPU<br>                         predictor=&#39;gpu_predictor&#39;,<br>                         booster=&#39;gbtree&#39;)  # Mimic AdaBoost<br><br># Preprocessing and model pipeline<br>model_pipeline = Pipeline(steps=[<br>    (&#39;preprocessor&#39;, preprocessor),<br>    (&#39;model&#39;, model)<br>])<br><br># Split the data into training, validation, and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=42)<br><br># Fit the model<br>model_pipeline.fit(X_train, y_train)<br><br># Evaluate the model<br>val_predictions = model_pipeline.predict(X_val)<br>test_predictions = model_pipeline.predict(X_test)<br><br># Print evaluation metrics<br>val_rmse = mean_squared_error(y_val, val_predictions, squared=False)<br>val_r2 = r2_score(y_val, val_predictions)<br>test_rmse = mean_squared_error(y_test, test_predictions, squared=False)<br>test_r2 = r2_score(y_test, test_predictions)<br><br>print(f&#39;AdaBoost-like XGBoost - Validation RMSE: {val_rmse}, R2: {val_r2}&#39;)<br>print(f&#39;AdaBoost-like XGBoost - Test RMSE: {test_rmse}, R2: {test_r2}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*aehnzJv8aPdNbZPLyGgcVQ.png" /></figure><blockquote><strong>Saving the Model</strong></blockquote><pre>import pickle<br># Save the model<br>pickle.dump(model_pipeline, open(&#39;xgboost_model.pk&#39;, &#39;wb&#39;))</pre><blockquote><strong>Comparative Performance Analysis</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*CIuQZoQ6F0UPgeAZYzFbFQ.png" /><figcaption><strong>Among the models explored, XGBoost emerged as the best performer, explaining 96.1% of the variation in airline fares and achieving an excellent balance between bias and variance. KNN performed reasonably well but faced challenges with high-dimensional data, limiting its ability to capture finer variations. The Decision Tree model provided high interpretability but was prone to overfitting, while linear models, though computationally efficient, lacked the flexibility to model complex non-linear relationships.</strong></figcaption></figure><p><strong>Finalizing the Best Model for Airline Fare Prediction</strong></p><p>After an exhaustive evaluation of various machine learning models, the <strong>XGBoost Regressor</strong> emerged as the most suitable and effective solution for predicting airline fares. This conclusion is grounded in the model’s ability to explain the maximum variation in ticket prices while maintaining robustness and scalability.</p><blockquote><strong>Why XGBoost Stands Out</strong></blockquote><ol><li><strong>Superior Performance</strong>:<br>XGBoost consistently outperformed all other models in validation and test metrics. It explained <strong>96.1% of the variation</strong> in airline ticket prices, striking the perfect balance between bias and variance. Its gradient-boosting approach ensured that even the smallest patterns in the dataset were captured and optimized.</li><li><strong>Effective Handling of Complexity</strong>:<br>The dataset included high-dimensional, categorical, and non-linear features. XGBoost’s advanced algorithms allowed it to handle these complexities seamlessly. Unlike linear models, which struggled with non-linear relationships, and simpler tree-based models, which tended to overfit, XGBoost excelled in capturing the intricacies of airline pricing mechanisms.</li><li><strong>Feature Interpretability</strong>:<br>By leveraging SHAP (Shapley Additive exPlanations) values, XGBoost provided clear and actionable insights into the factors driving ticket prices. The top predictors identified were:</li></ol><ul><li><strong>BookingLeadTime</strong>: A shorter lead time consistently drove up ticket prices, reflecting the industry’s demand-based pricing strategies.</li><li><strong>Total Stops</strong>: Non-stop flights were cheaper than multi-stop options, correlating with operational costs and convenience premiums.</li><li><strong>TravelSeason</strong>: Seasonal trends, particularly during holiday periods, revealed spikes in ticket prices due to increased demand.</li></ul><p><strong>4. Robustness and Generalization</strong>:<br>The XGBoost model demonstrated superior robustness, effectively avoiding overfitting while generalizing well across unseen data. This was reflected in the model’s consistently high R² scores on both validation and test sets, confirming its reliability for real-world applications.</p><p><strong>5. Scalability for Deployment</strong>:<br>XGBoost is optimized for speed and scalability, making it an ideal choice for deployment. Its adaptability to large datasets and efficient resource usage ensures it can handle production-level data without compromising performance.</p><blockquote><strong>Comparative Advantage Over Other Models</strong></blockquote><ol><li><strong>Linear Models (Lasso and Ridge Regression)</strong>:<br>Linear models were computationally efficient and effective for simpler relationships but struggled to capture the dataset’s inherent complexity. This limited their ability to explain large variations in ticket prices.</li><li><strong>KNN and Decision Tree Regressors</strong>:</li></ol><ul><li><strong>KNN</strong>: Though effective for smaller datasets, it faced challenges with high-dimensional data and was computationally expensive for large-scale predictions.</li><li><strong>Decision Tree</strong>: Provided excellent interpretability but was prone to overfitting, which reduced its reliability on unseen data despite hyperparameter tuning.</li></ul><blockquote><strong>Key Highlights of the XGBoost Model</strong></blockquote><ul><li><strong>Efficiency</strong>: XGBoost handled missing data and imbalanced datasets with ease, ensuring accurate predictions even in challenging scenarios.</li><li><strong>Scalability</strong>: The model’s ability to process large volumes of data makes it highly suitable for real-world airline fare prediction systems.</li><li><strong>Feature Importance Insights</strong>: XGBoost provided not only predictions but also valuable insights into the pricing dynamics of the airline industry, helping stakeholders optimize their strategies.</li><li><strong>Consistency Across Datasets</strong>: The model demonstrated stable performance across training, validation, and test datasets, reinforcing its reliability for deployment.</li></ul><blockquote><strong>Broader Impact and Use Cases</strong></blockquote><ol><li><strong>For Travel Platforms</strong>:<br>Integrating the XGBoost model into online travel booking systems can enhance the user experience by providing real-time fare predictions and recommendations, helping platforms stand out in a competitive market.</li><li><strong>For Airlines</strong>:<br>The model empowers airlines to refine their pricing strategies by understanding the key factors influencing ticket prices. This can lead to more dynamic pricing models, optimized revenue management, and better alignment with customer expectations.</li><li><strong>For Travellers:</strong><br>By providing precise predictions of ticket prices, travellers can make informed booking decisions, save money, and plan their journeys more effectively. Insights into lead times and travel seasons empower users to identify the most cost-effective flights and optimize their travel plans</li></ol><p><strong><em>The XGBoost Regressor proved to be the most effective model for predicting airline ticket prices, showing excellent accuracy and reliability. This journey, from data analysis to model optimization, has been both challenging and enriching, providing a deeper understanding of machine learning techniques and their practical use. While this is not an industry-level project, it sets a strong foundation for further exploration in predictive modelling and serves as a significant step forward in my learning journey.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6922ffce1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>