<?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 Atharva Deshpande  on Medium]]></title>
        <description><![CDATA[Stories by Atharva Deshpande  on Medium]]></description>
        <link>https://medium.com/@atharva.deshpande.925?source=rss-6c9f3a234533------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3ohl69LEZZnl7wuF</url>
            <title>Stories by Atharva Deshpande  on Medium</title>
            <link>https://medium.com/@atharva.deshpande.925?source=rss-6c9f3a234533------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:26:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atharva.deshpande.925/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[Network Anomaly Detection using NSL-KDD Dataset]]></title>
            <link>https://medium.com/@atharva.deshpande.925/network-anomaly-detection-using-nsl-kdd-dataset-1adbbde1830f?source=rss-6c9f3a234533------2</link>
            <guid isPermaLink="false">https://medium.com/p/1adbbde1830f</guid>
            <dc:creator><![CDATA[Atharva Deshpande ]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 08:12:45 GMT</pubDate>
            <atom:updated>2025-12-29T08:45:16.935Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Project Github: </em><a href="https://github.com/ad250997/Network-Anomaly-Detection"><em>Click here</em></a></p><p><em>Tableau Dashboard: </em><a href="https://public.tableau.com/views/NetworkAnomalyDetection_17668554667360/Dashboard1?:language=en-US&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link"><em>Click here</em></a></p><h3>Contents</h3><ol><li>Introduction</li><li>Exploratory Data Analysis (EDA)</li><li>Hypothesis Testing</li><li>Pre-processing the Data for Modelling</li><li>Modelling — Binary Classification (Normal vs. Attack)</li><li>Modelling — Multiclass classification (Attack Type — DoS/Probe/R2L/U2R)</li><li>Deployment</li><li>Conclusion</li></ol><h3>1. Introduction</h3><h4>1.1 Problem Statement</h4><p>In the realm of cybersecurity, network anomaly detection is a critical task that involves identifying unusual patterns or behaviors that deviate from the norm within network traffic. These anomalies could signify a range of security threats, from compromised devices and malware infections to large-scale cyber-attacks like DoS (Denial of Service). The challenge lies in accurately detecting these anomalies in real-time, amidst the vast and continuous streams of network data, which are often noisy and heterogeneous.</p><p>In this project, the objective is to design an <strong>end-to-end machine learning pipeline for intrusion detection</strong>, covering the entire lifecycle: exploratory data analysis (EDA), hypothesis formulation and testing, model training, evaluation, and deployment considerations. The system follows a <strong>two-stage architecture</strong>:</p><ol><li>Binary classification to detect whether a network connection is normal or malicious.</li><li>Multiclass classification to identify the specific attack category once an intrusion is detected.</li></ol><h4>1.2 Objectives</h4><p>The task is to analyze network connection records and determine:</p><ul><li>Whether a given connection represents a normal interaction or an attack</li><li>If an attack is present, what type of attack it belongs to (e.g., DoS, Probe, R2L, U2R)</li></ul><p>For this project, the famous NSL-KDD dataset was used. Each row of this dataset represents a unique network record. Each network record consists of Basic Connection Features, Content-Related Features, Time-Related Traffic Features and Host-Based Traffic Features.</p><h3>2. Exploratory Data Analysis</h3><p>The dataset used in this project is derived from the <strong>NSL-KDD intrusion detection </strong>dataset. It contains labeled network connection records, each described by a mix of numerical and categorical features capturing traffic volume, protocol behavior, error rates, and host-level statistics.</p><pre>raw_data = pd.read_csv(<br>            &#39;.\Network_anomaly_data.csv&#39;)<br>raw_data.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*v4jItNjp7-5PBgubol982A.png" /></figure><p><strong>Dataset characteristics:</strong></p><ul><li>~126,000 network connections</li><li>42 original features</li><li>No missing values</li><li>No duplicate records</li><li>Mix of continuous, discrete, and categorical variables</li></ul><p><strong>Target variables:</strong></p><ul><li>attack: Specific attack label</li></ul><p>Using this target, two more target variables are created for binary and multiclass classification respectively.</p><ul><li>attackflag: Binary indicator (Normal vs Attack)</li><li>attacktype: Aggregated attack category</li></ul><h4><strong>Defining the Four Major Attack Types</strong></h4><p>The Network Attacks are widely classified into the following 4 categories:</p><p><strong>Denial of Service (DoS)</strong></p><p>These attacks aim to disrupt availability by overwhelming a target with excessive traffic or malformed requests, causing legitimate users to be unable to access services. E.g. These attacks try to shut down a website or service by flooding it with too many requests, making it unavailable to real users.</p><p><strong>Probe</strong></p><p>These attacks focus on reconnaissance, where attackers scan networks or hosts to discover open ports, running services, or potential vulnerabilities before launching more targeted attacks. E.g. These attacks are like digital scouting, where attackers quietly look for weak points or open doors in a system.</p><p><strong>Remote to Local (R2L)</strong></p><p>These attacks occur when an external attacker gains unauthorized local access by exploiting weaknesses such as weak passwords or misconfigurations, often without generating high traffic volumes. E.g. These attacks happen when someone outside the system manages to log in without permission, often by guessing or stealing credentials.</p><p><strong>User to Root (U2R)</strong></p><p>These attacks involve a local user escalating privileges to gain root or administrative access, typically through software vulnerabilities, and are rare but highly impactful. E.g. These attacks occur when a user with limited access manages to gain full control of a system, which is rare but very serious.</p><pre>df = raw_data.copy(deep=True)<br>df[&#39;attackflag&#39;] = raw_data[&#39;attack&#39;].apply(<br>                        lambda x: 0 if x==&#39;normal&#39; else 1)<br><br>def type_of_attack(attack):<br>    # Denial of Service (DoS) attacks<br>    DoS = [<br>        &quot;back&quot;,<br>        &quot;land&quot;,<br>        &quot;neptune&quot;,<br>        &quot;pod&quot;,<br>        &quot;smurf&quot;,<br>        &quot;teardrop&quot;,<br>        &quot;mailbomb&quot;,<br>        &quot;apache2&quot;,<br>        &quot;processtable&quot;,<br>        &quot;udpstorm&quot;<br>    ]<br><br>    # Probe (surveillance / scanning) attacks<br>    Probe = [<br>        &quot;satan&quot;,<br>        &quot;ipsweep&quot;,<br>        &quot;nmap&quot;,<br>        &quot;portsweep&quot;,<br>        &quot;mscan&quot;,<br>        &quot;saint&quot;<br>    ]<br><br>    # Remote to Local (R2L) attacks<br>    R2L = [<br>        &quot;guess_passwd&quot;,<br>        &quot;ftp_write&quot;,<br>        &quot;imap&quot;,<br>        &quot;phf&quot;,<br>        &quot;multihop&quot;,<br>        &quot;warezmaster&quot;,<br>        &quot;warezclient&quot;,<br>        &quot;spy&quot;,<br>        &quot;xlock&quot;,<br>        &quot;xsnoop&quot;,<br>        &quot;snmpguess&quot;,<br>        &quot;snmpgetattack&quot;,<br>        &quot;httptunnel&quot;,<br>        &quot;sendmail&quot;,<br>        &quot;named&quot;<br>    ]<br><br>    # User to Root (U2R) attacks<br>    U2R = [<br>        &quot;buffer_overflow&quot;,<br>        &quot;loadmodule&quot;,<br>        &quot;rootkit&quot;,<br>        &quot;perl&quot;,<br>        &quot;sqlattack&quot;,<br>        &quot;xterm&quot;,<br>        &quot;ps&quot;<br>    ]<br>    if attack == &#39;normal&#39;:<br>        return &#39;normal&#39;<br>    elif attack in DoS:<br>        return &#39;DoS&#39;<br>    elif attack in Probe:<br>        return &#39;Probe&#39;<br>    elif attack in R2L:<br>        return &#39;R2L&#39;<br>    elif attack in U2R:<br>        return &#39;U2R&#39;<br>    <br>    return &#39;other&#39;<br><br>df[&#39;attacktype&#39;] = df[&#39;attack&#39;].apply(type_of_attack)<br>attacks_DoS = df[df[&#39;attacktype&#39;]==&#39;DoS&#39;][&#39;attack&#39;]<br>attacks_Probe = df[df[&#39;attacktype&#39;]==&#39;Probe&#39;][&#39;attack&#39;]<br>attacks_R2L = df[df[&#39;attacktype&#39;]==&#39;R2L&#39;][&#39;attack&#39;]<br>attacks_U2R = df[df[&#39;attacktype&#39;]==&#39;U2R&#39;][&#39;attack&#39;]<br>attacks_all = df[df[&#39;attack&#39;] != &#39;normal&#39;][&#39;attack&#39;]<br><br>attacktypes = df[&#39;attacktype&#39;].copy(deep=True)<br>attacktypes_within_attacks = df[df[&#39;attackflag&#39;]==1][&#39;attacktype&#39;].copy(deep=True)<br><br>attackflags_text = df[&#39;attackflag&#39;].copy(deep=True).map({0:&#39;normal&#39;,1:&#39;attack&#39;})</pre><h4><strong>Removal of Features with very high Modal Frequency (&gt;99%)</strong></h4><p>Initial inspection revealed several features with <strong>modal frequencies exceeding 99%</strong>, meaning they took a single value for nearly all observations. Such features contribute minimal predictive information while increasing model complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*t7sebORY1dWTyjgiy1Aozw.png" /></figure><p>To validate their removal:</p><ul><li>Attack distributions were examined for non-modal values</li><li>Mutual Information (MI) scores were computed against the target</li></ul><pre>print(&#39;MUTUAL INFORMATION SCORES:&#39;)<br>for col in df.drop(columns=&#39;attack&#39;): <br>    X = df[[col]].apply(lambda x: pd.factorize(x)[0])<br>    y = df[&#39;attack&#39;]<br><br>    # For Classification<br>    mi_score = mutual_info_classif(X, y, discrete_features=[True])<br>    if mi_score &lt;= 0.1:<br>        print(f&quot;{col.upper()}{&#39; &#39;*(30-len(col)-6)}{round(mi_score[0],4)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*D8CSnh1LBsJGOS2p7Kj24Q.png" /></figure><p>These features with extremely low MI scores and no meaningful attack association were dropped. This step reduced dimensionality while preserving signal, improving both model interpretability and training efficiency.</p><h3>2.1 Numerical and Categorical Feature Separation</h3><p>Features were split into:</p><ul><li><strong>Numerical features</strong>: Traffic volumes, rates, counts</li><li><strong>Categorical features</strong>: Protocol, service, connection flag</li></ul><p>This separation guided visualization choices and later preprocessing strategies.</p><h3>2.2 Univariate Analysis</h3><h4>2.2.1 Numerical Features</h4><p>Univariate analysis revealed strong right skewness across most numerical features. The majority of connections exhibited small values, with rare but extreme outliers.</p><p>Key observations:</p><ul><li>Traffic volume features (srcbytes, dstbytes) showed heavy tails</li><li>Count-based features indicated bursty connection behavior</li><li>Error-rate features clustered near 0 or 1, suggesting sharp transitions between normal and abnormal traffic</li><li>Several features were sparse but potentially high-impact (e.g., numcompromised)</li></ul><p>These distributions motivated the use of <strong>logarithmic transformations</strong> prior to linear modeling.</p><pre>grid_size = int(np.ceil((df_num.shape[1]-1)**0.5))<br><br># KDE PLOTS<br>plt.figure(figsize=(20,16))<br>for i,col in enumerate(df_num):<br>    if col != &#39;attackflag&#39;:<br>        plt.subplot(grid_size, grid_size, i+1)<br>        sns.kdeplot(data=df_num, x=col)<br>plt.tight_layout()<br>plt.show()<br><br># BOX PLOTS<br>plt.figure(figsize=(16,20))<br>for i,col in enumerate(df_num):<br>    if col != &#39;attackflag&#39;:<br>        plt.subplot(grid_size, grid_size, i+1)    <br>        sns.boxplot(data=df_num, y=col, fliersize=1)<br>        plt.xlabel(col)<br>        plt.ylabel(&#39;&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fFM84aK9jfVz2ueuncsBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7k5vHXB-gFo7vwM8O5K_5g.png" /></figure><ul><li>Most features exhibit <strong>strong right skewness</strong>, with values concentrated near zero and a small number of extreme observations.</li><li><strong>Duration, source bytes, and destination bytes show particularly heavy tails</strong>, indicating mostly short, low-volume connections with a few very large transfers.</li><li>Count-based variables (e.g., count, srvcount, dsthostcount, dsthostsrvcount) have long right tails, suggesting repetitive or bursty connection behavior in a minority of cases.</li><li>Outliers are prevalent across many features, especially in traffic volume and connection count metrics, likely corresponding to anomalous or attack-related activity.</li><li>numcompromised is mostly zero with rare large values, making it a sparse but potentially strong indicator of compromise.</li><li>Binary or near-binary behavior is evident in loggedin, clearly separating logged-in and non-logged-in sessions.</li><li>Many rate-based features (e.g., serrorrate, srvserrorrate, rerrorrate, srvrerrorrate) cluster near 0 with a secondary peak near 1, indicating sharp transitions between normal and abnormal traffic.</li><li>Host-based rate features (dsthost*rate) consistently show bimodal distributions, suggesting strong discriminative power for intrusion detection.</li><li>Service similarity measures (samesrvrate, dsthostsamesrvrate) display clear separation between diverse-service normal traffic and repeated-service attack patterns.</li><li>Difference-based service rates (diffsrvrate, dsthostdiffsrvrate) are mostly close to zero, indicating limited service switching in most connections.</li><li>The dominance of extreme values implies a need for log scaling prior to modeling.</li></ul><h4>2.2.2 Categorical Features</h4><pre>grid_size = int(np.ceil((df_cat.shape[1]-3)**0.5))<br><br>plt.figure(figsize=(20,16))<br>for i,col in enumerate(df_cat):<br>    if &#39;attack&#39; not in col:<br>        plt.subplot(grid_size, grid_size, i+1)<br>        sns.countplot(data=df_cat, x=col)<br>        plt.xlabel(col)<br>        plt.xticks(rotation=90)<br>        plt.ylabel(&#39;&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktICBFtAVSJc3CV2yV12zQ.png" /></figure><ul><li><strong>TCP dominates the protocol distribution</strong>, accounting for the majority of connections, while UDP is significantly less frequent and ICMP appears relatively rare.</li><li>The <strong>service feature is highly imbalanced</strong>, with a small number of services (e.g., HTTP-related and common network services) accounting for most connections, and many services occurring very infrequently.</li><li>The long tail in the service distribution indicates <strong>high categorical sparsity</strong>, which may require grouping rare services or using robust encoding techniques.</li><li><strong>Connection flags are strongly skewed</strong>, with SF being the most common state, followed by S0, while other flags occur much less frequently.</li><li>The prevalence of S0, REJ, and other non-SF flags suggests a <strong>substantial presence of failed or incomplete connections</strong>, which can be indicative of scanning or attack behavior.</li><li>Overall, the categorical features exhibit <strong>class imbalance</strong>, implying that careful encoding and imbalance-aware modeling strategies are necessary.</li></ul><h3>2.3 Bivariate Analysis (Normal vs Attack)</h3><h4>2.3.1 Class Distribution</h4><pre>plt.figure(figsize=(16,8))<br>plt.title(&#39;Attack Vs Normal&#39;)<br>plt.pie(attackflags_text.value_counts(), <br>        labels=attackflags_text.value_counts().index,<br>        explode=[0,0] + [0.5]*(attackflags_text.nunique()-2), <br>        autopct=&#39;%1.1f%%&#39;, <br>        counterclock=False,<br>        startangle=90, <br>        pctdistance=0.8, <br>        labeldistance=1,<br>        colors=[&#39;lightgreen&#39;,&#39;maroon&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjZ4r5VKOf3vaDXXxnY4fg.png" /></figure><pre>plt.figure(figsize=(8,8))<br>plt.pie(attacktypes_within_attacks.value_counts(), <br>        labels=attacktypes_within_attacks.value_counts().index,<br>        explode=[0,0] + [0.5]*(attacktypes_within_attacks.nunique()-2), <br>        autopct=&#39;%1.1f%%&#39;, <br>        counterclock=False,<br>        pctdistance=0.8, <br>        labeldistance=1,<br>        colors=[&#39;maroon&#39;,&#39;red&#39;,&#39;tomato&#39;,&#39;salmon&#39;], )<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faI5ww6ZxfEL3AgOvkeHAA.png" /></figure><ul><li><strong>The dataset is fairly balanced between normal and attack traffic</strong>, with normal connections making up ~53.5% and attacks ~46.5%, reducing severe class imbalance concerns for model training.</li><li><strong>DoS attacks overwhelmingly dominate the attack landscape</strong>, accounting for ~78% of all attacks, indicating the dataset is heavily biased toward availability-based attack patterns.</li><li><strong>R2L and U2R attacks are extremely rare</strong>, together contributing less than 2% of attacks, which may make them difficult to learn without resampling or specialized modeling techniques.</li></ul><h4>2.3.2 Numerical Features by Attack Status</h4><pre>palette = {0:&#39;green&#39;,1:&#39;maroon&#39;}<br>grid_size = int(np.ceil((df_num.shape[1]-1)**0.5))<br><br># KDE PLOTS<br>plt.figure(figsize=(20,16))<br>for i,col in enumerate(df_num):<br>    if col != &#39;attackflag&#39;:<br>        plt.subplot(grid_size, grid_size, i+1)<br>        sns.kdeplot(data=df_num, <br>                    x=col, <br>                    hue=&#39;attackflag&#39;, <br>                    palette=palette)<br>plt.tight_layout()<br>plt.show()<br><br># BOX PLOTS<br>plt.figure(figsize=(16,20))<br>for i,col in enumerate(df_num):<br>    if col != &#39;attackflag&#39;:<br>        plt.subplot(grid_size, grid_size, i+1)    <br>        sns.boxplot(data=df_num, <br>                    y=col, <br>                    hue=&#39;attackflag&#39;, <br>                    fliersize=1,<br>                    palette=palette)<br>        plt.xlabel(col)<br>        plt.ylabel(&#39;&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOfiDsge6VnV3h1eGWrEbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH3d_8fusWGCV8wrzDeX9Q.png" /></figure><ul><li><strong>Attack traffic shows extreme skewness in connection behavior</strong>, with much higher count, srvcount, and dsthostcount values compared to normal traffic, indicating repeated or bursty connection attempts typical of scanning and flooding attacks.</li><li><strong>Rate-based features are the strongest discriminators</strong>, especially serrorrate, srvserrorrate, same_srv_rate, and their dsthost variants, where attack connections cluster near extreme values (close to 0 or 1) while normal traffic remains more spread out.</li><li><strong>Error-related metrics are heavily associated with attacks</strong>, as attack-labeled flows exhibit significantly higher SYN error and service error rates, suggesting failed or half-open connections common in DoS and probing activities.</li><li><strong>Login and privilege-related features are highly imbalanced</strong>, with loggedin and numcompromised almost exclusively indicating normal behavior, while attacks rarely involve successful authentication.</li><li><strong>Host-based aggregation features (</strong><strong>dsthost*) amplify separation</strong>, where attack traffic consistently shows abnormal consistency across hosts and services, reflecting coordinated or automated attack patterns.</li></ul><h4>2.3.3 Categorical Features by Attack Status</h4><pre>grid_size = int(np.ceil((df_cat.shape[1]-3)**0.5))<br><br>plt.figure(figsize=(16,16))<br>for i,col in enumerate(df_cat):<br>    if col not in [&#39;attack&#39;,&#39;attacktype&#39;,&#39;attackflag&#39;]:<br>        plt.subplot(grid_size, grid_size, i+1)<br>        sns.countplot(data=df_cat, <br>                      x=col, <br>                      hue=&#39;attackflag&#39;, <br>                      palette=palette)<br>        plt.xlabel(col)<br>        plt.xticks(rotation=90)<br>        plt.ylabel(&#39;&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVAamY143lk30K5Bv-amCQ.png" /></figure><ul><li><strong>TCP is the most commonly used protocol</strong> for both normal and attack traffic, indicating it is the primary communication channel and a major attack surface.</li><li><strong>ICMP traffic shows a disproportionately high number of attacks</strong> compared to normal usage, suggesting frequent use in reconnaissance and flooding activities.</li><li>UDP traffic is largely associated with normal behavior, with relatively few attack instances observed in the dataset.</li><li>Services such as <strong>ftp_data, private, http, eco_i, ecr_i, etc.</strong> exhibit higher attack frequencies, highlighting that publicly accessible services are more frequently targeted.</li><li>Normal traffic is dominated by the SF flag (successful connections), while <strong>attack traffic shows higher occurrences of S0, REJ, and RSTR flags</strong>, reflecting failed or abnormal connection attempts.</li></ul><h3>2.4 Multivariate Analysis (Attack Types)</h3><p>Multiclass analysis showed:</p><ul><li>DoS attacks dominated by a small number of attack variants</li><li>Probe attacks more diverse</li><li>R2L and U2R extremely sparse and overlapping with normal behavior</li></ul><p>This justified a <strong>two-stage modeling strategy</strong> instead of a single multiclass classifier.</p><h4>2.4.1 Attack Types Distribution</h4><pre>plt.figure(figsize=(16,12))<br><br>x = {<br>    &#39;DoS&#39;:attacks_DoS,<br>    &#39;Probe&#39;:attacks_Probe,<br>    &#39;R2L&#39;:attacks_R2L,<br>    &#39;U2R&#39;:attacks_U2R<br>}<br><br>i=1<br>colors = [&#39;maroon&#39;,&#39;red&#39;,&#39;tomato&#39;,&#39;salmon&#39;]<br>total = len(attacktypes_within_attacks)<br>for k,s in x.items():<br>    vc = s.value_counts()<br>    plt.subplot(2,2,i)<br>    plt.title(f&#39;Distribution of {k} attacks&#39;,size=20)<br>    ax = sns.countplot(y=s,<br>                  order=vc.index,<br>                  color=colors[i-1])<br>    subtotal = len(s)<br>    for p in ax.patches:<br>        count = int(p.get_width())<br>        text1 = str(round(count/subtotal*100,1)) + r&quot;% of &quot; + k + &quot; attacks&quot;<br>        text2 = str(round(count/total*100,1)) + r&quot;% of all attacks&quot;<br>        text = text1 + &#39;\n&#39; + text2<br>        ax.annotate(text,<br>                    (count, p.get_y() + p.get_height()/2),<br>                    ha=&#39;left&#39;, <br>                    va=&#39;center&#39;)<br>    ax.spines[&#39;top&#39;].set_visible(False)<br>    ax.spines[&#39;right&#39;].set_visible(False)<br>    ax.yaxis.set_ticks_position(&#39;none&#39;)<br>    plt.xlabel(&#39;&#39;)<br>    # plt.xticks(rotation=90)<br>    i+=1<br>    <br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7T8aywJlltdnJa6-j1UuA.png" /></figure><ul><li><strong>DoS attacks are overwhelmingly dominated by the neptune </strong>attack, accounting for nearly 90% of all DoS incidents and over 70% of total attacks, indicating a severe class imbalance.</li><li><strong>Probe attacks are more evenly distributed, with satan, ipsweep, and portsweep together forming the majority</strong>, suggesting diverse reconnaissance techniques.</li><li>R2L attacks are highly concentrated, with <strong>warezclient</strong> making up almost 90% of R2L cases, while other R2L attack types occur very rarely.</li><li>U2R attacks are extremely scarce overall, but <strong>buffer_overflow</strong> is the most prominent within this category, representing more than half of U2R attacks.</li><li>The attack dataset is heavily skewed toward a few dominant attack types, which may bias machine learning models if not handled with resampling or class-weighting techniques.</li><li><strong>Rare attack classes (especially U2R and minor R2L types) are difficult to learn from due to low frequency, increasing the risk of false negatives in intrusion detection systems.</strong></li></ul><h4>2.4.2 Numerical Features by Attack Types</h4><pre>df_num1 = df_num.copy(deep=True)<br>df_num1[&#39;attacktype&#39;] = df[&#39;attacktype&#39;]<br><br>palette = {<br>    &#39;normal&#39;:&#39;green&#39;,<br>    &#39;DoS&#39;:&#39;maroon&#39;,<br>    &#39;Probe&#39;:&#39;red&#39;,<br>    &#39;R2L&#39;:&#39;tomato&#39;,<br>    &#39;U2R&#39;:&#39;salmon&#39;<br>}<br><br>grid_ht = int(np.ceil((df_num1.shape[1]-2)/3))<br><br>plt.figure(figsize=(16,20))<br>i=1<br>for col in df_num1:<br>    if col not in [&#39;attacktype&#39;,&#39;attackflag&#39;]:<br>        plt.subplot(grid_ht, 3, i)<br>        sns.kdeplot(data=df_num1, <br>                    x=col, <br>                    hue=&#39;attacktype&#39;, <br>                    palette=palette)<br>        i+=1<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JybUza0-GmRGtfEWOqTREQ.png" /></figure><ul><li>Duration, srcbytes, and dstbytes show heavy right-skew; DoS traffic concentrates near zero duration with extreme byte outliers.</li><li>Loggedin clearly separates classes: normal connections peak near 1, while most attack types cluster near 0.</li><li>Count and srvcount are higher and more dispersed for DoS and Probe attacks, indicating repeated connection attempts.</li><li>Error-rate features (serrorrate, srvserrorrate, rerrorrate) peak near 1 for DoS, while normal traffic stays near 0.</li><li>Host-based features (dsthostcount, dsthostsrvcount) show strong separation, with attacks exhibiting higher densities at large values.</li><li>R2L and U2R often overlap with normal in many distributions, suggesting they are harder to distinguish using single features.</li></ul><h4>2.4.2 Categorical Features by Attack Types</h4><pre>grid_ht = int(np.ceil((df_cat.shape[1]-3)/2))<br><br>plt.figure(figsize=(16,20))<br>i=1<br>for col in df_cat:<br>    if col not in [&#39;attack&#39;,&#39;attacktype&#39;,&#39;attackflag&#39;]:<br>        plt.subplot(grid_ht, 2, i)<br>        sns.countplot(data=df_cat, <br>                      x=col, <br>                      hue=&#39;attacktype&#39;, <br>                      palette=palette)<br>        plt.xlabel(col)<br>        plt.xticks(rotation=90)<br>        plt.ylabel(&#39;&#39;)<br>        i+=1<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRrdMphNQMA9z0pRTDim7A.png" /></figure><ul><li>TCP dominates across all classes, with normal and DoS traffic heavily concentrated on TCP, while ICMP is more associated with Probe attacks.</li><li>A small subset of services (e.g., http, private) accounts for the majority of normal traffic, whereas attacks spread across more services.</li><li>DoS traffic shows strong association with specific services and protocol combinations, indicating repetitive attack patterns.</li><li>Flag distribution differs clearly: normal traffic is dominated by SF, while DoS and Probe attacks show higher counts of S0, REJ, and RSTR flags.</li></ul><h3>3. Hypothesis Testing</h3><h4>3.1 Effect of Unusually High or Low Traffic Volume (bytes Transferred)</h4><pre>df1 = raw_data.copy(deep=True)<br>df1[&#39;attackflag&#39;] = df1[&#39;attack&#39;].apply(lambda x: 0 if x==&#39;normal&#39; else 1)</pre><pre>H0 = &#39;The mean srcbytes for normal connections IS EQUAL TO the mean srcbytes for attacked connections.&#39;<br>Ha = &#39;The mean srcbytes for normal connections DIFFERS from the mean srcbytes for attacked connections.&#39;<br><br>srcbytes_normal = df1[df1[&#39;attackflag&#39;]==0][&#39;srcbytes&#39;]<br>srcbytes_attack = df1[df1[&#39;attackflag&#39;]==1][&#39;srcbytes&#39;]<br><br>t_stat, p_value = stats.ttest_ind(srcbytes_normal, srcbytes_attack, equal_var=False)<br>print(f&#39;T-statistic = {t_stat:.4f}&#39;)<br><br>if p_value &lt; 0.05:<br>    # reject H0<br>    print(f&#39;P-value = {p_value:.4f} &lt; 0.05&#39;)<br>    print(&#39;Decision: Reject H0.&#39;)<br>    print(&#39;Conclusion:\n&#39;,Ha)<br>else:<br>    # Fail to reject H0<br>    print(f&#39;P-value = {p_value:.4f} &gt;= 0.05&#39;)<br>    print(&#39;Decision: Fail to reject H0&#39;)<br>    print(&#39;Conclusion:\nInsufficient evidence to conclude statistically significant difference in mean srcbytes of normal vs attacked connections.&#39;)</pre><pre>T-statistic = -1.9616<br>P-value = 0.0498 &lt; 0.05<br>Decision: Reject H0.<br>Conclusion:<br> The mean srcbytes for normal connections DIFFERS from the mean srcbytes for attacked connections.</pre><pre>H0 = &#39;The mean dstbytes for normal connections IS EQUAL TO the mean dstbytes for attacked connections.&#39;<br>Ha = &#39;The mean dstbytes for normal connections DIFFERS from the mean dstbytes for attacked connections.&#39;<br><br>dstbytes_normal = df1[df1[&#39;attackflag&#39;]==0][&#39;dstbytes&#39;]<br>dstbytes_attack = df1[df1[&#39;attackflag&#39;]==1][&#39;dstbytes&#39;]<br><br>t_stat, p_value = stats.ttest_ind(dstbytes_normal, srcbytes_attack, equal_var=False)<br>print(f&#39;T-statistic = {t_stat:.4f}&#39;)<br>print(f&#39;P-value = {p_value:.4f}&#39;)<br>if p_value &lt; 0.05:<br>    # reject H0<br>    print(&#39;Decision: Reject H0.&#39;)<br>    print(&#39;Conclusion:\n&#39;, Ha)<br>else:<br>    # Fail to reject H0<br>    print(&#39;Decision: Fail to reject H0&#39;)<br>    print(&#39;Conclusion:\nInsufficient evidence to conclude statistically significant difference in mean dstbytes of normal vs attacked connections.&#39;)</pre><pre>T-statistic = -2.2117<br>P-value = 0.0270<br>Decision: Reject H0.<br>Conclusion:<br> The mean dstbytes for normal connections DIFFERS from the mean dstbytes for attacked connections.</pre><h4>3.2 Impact of Protocol Type on Anomaly Detection</h4><pre>H0 = &#39;Attack status and protocol type are INDEPENDENT.&#39;<br>Ha = &#39;Attack status and protocol type are ASSOCIATED.&#39;<br><br>table = pd.crosstab(df1[&#39;attack&#39;], df1[&#39;protocoltype&#39;])<br><br>chi2, p_value, dof, expected_freq = stats.chi2_contingency(table)<br><br>if p_value &lt; 0.05:<br>    # reject H0<br>    print(f&#39;P-value = {p_value:.4f} &lt; 0.05&#39;)<br>    print(&#39;Decision: Reject H0.&#39;)<br>    print(&#39;Conclusion:\n&#39;, Ha)<br>else:<br>    # Fail to reject H0<br>    print(f&#39;P-value = {p_value:.4f} &gt;= 0.05&#39;)<br>    print(&#39;Decision: Fail to reject H0&#39;)<br>    print(&#39;Conclusion:\nInsufficient evidence to conclude statistically significant association between attack status and protocol type.&#39;)</pre><pre>P-value = 0.0000 &lt; 0.05<br>Decision: Reject H0.<br>Conclusion:<br> Attack status and protocol type are ASSOCIATED.</pre><h4>3.3 Role of Service in Anomaly Detection</h4><pre>H0 = &#39;Attack status and service type are INDEPENDENT.&#39;<br>Ha = &#39;Attack status and service type are STATISTICALLY ASSOCIATED.&#39;<br><br>table = pd.crosstab(df1[&#39;attack&#39;], df1[&#39;service&#39;])<br><br>chi2, p_value, dof, expected_freq = stats.chi2_contingency(table)<br><br>if p_value &lt; 0.05:<br>    # reject H0<br>    print(f&#39;P-value = {p_value:.4f} &lt; 0.05&#39;)<br>    print(&#39;Decision: Reject H0.&#39;)<br>    print(&#39;Conclusion: &#39;, Ha)<br>else:<br>    # Fail to reject H0<br>    print(f&#39;P-value = {p_value:.4f} &gt;= 0.05&#39;)<br>    print(&#39;Decision: Fail to reject H0&#39;)<br>    print(&#39;Conclusion:\nInsufficient evidence to conclude statistically significant association between attack status and service type.&#39;)</pre><pre>P-value = 0.0000 &lt; 0.05<br>Decision: Reject H0.<br>Conclusion:  Attack status and service type are STATISTICALLY ASSOCIATED.</pre><h4>3.4 Coonection Status (Flag) and Anomalies</h4><pre>X = pd.get_dummies(df1[&#39;flag&#39;], drop_first=True, dtype=int)<br>X = sm.add_constant(X)<br>y = df1[&#39;attackflag&#39;]<br><br>model = sm.Logit(y, X)<br>result = model.fit_regularized(alpha=1.0)<br><br>print(result.summary())</pre><pre>Optimization terminated successfully    (Exit mode 0)<br>            Current function value: 0.3309826988360228<br>            Iterations: 204<br>            Function evaluations: 204<br>            Gradient evaluations: 204<br>                           Logit Regression Results                           <br>==============================================================================<br>Dep. Variable:             attackflag   No. Observations:               125973<br>Model:                          Logit   Df Residuals:                   125962<br>Method:                           MLE   Df Model:                           10<br>Date:                Sun, 28 Dec 2025   Pseudo R-squ.:                  0.5212<br>Time:                        07:59:36   Log-Likelihood:                -41666.<br>converged:                       True   LL-Null:                       -87016.<br>Covariance Type:            nonrobust   LLR p-value:                     0.000<br>==============================================================================<br>                 coef    std err          z      P&gt;|z|      [0.025      0.975]<br>------------------------------------------------------------------------------<br>const          1.1541      0.345      3.342      0.001       0.477       1.831<br>REJ             7e-16      0.346   2.02e-15      1.000      -0.678       0.678<br>RSTO           0.6543      0.353      1.854      0.064      -0.037       1.346<br>RSTOS0         3.5657      1.108      3.218      0.001       1.394       5.737<br>RSTR           1.5848      0.356      4.456      0.000       0.888       2.282<br>S0             3.4224      0.349      9.794      0.000       2.737       4.107<br>S1            -5.4308      0.568     -9.570      0.000      -6.543      -4.319<br>S2            -3.7267      0.489     -7.627      0.000      -4.684      -2.769<br>S3            -3.3248      0.584     -5.691      0.000      -4.470      -2.180<br>SF            -2.8565      0.346     -8.268      0.000      -3.534      -2.179<br>SH             3.3144      0.670      4.949      0.000       2.002       4.627<br>==============================================================================</pre><pre>llr_p_value = result.llr_pvalue<br><br>if llr_p_value &lt; 0.05:<br>    print(f&quot;LLR p-value = {llr_p_value:.4f} &lt; 0.05&quot;)<br>    print(&quot;Decision: Reject H0.&quot;)<br>    print(&quot;Conclusion: Error flag and attack status are STATISTICALLY ASSOCIATED.&quot;)<br>else:<br>    print(f&quot;LLR p-value = {llr_p_value:.4f} &gt;= 0.05&quot;)<br>    print(&quot;Decision: Fail to reject H0.&quot;)<br>    print(&quot;Conclusion:\nInsufficient evidence to conclude statistically significant association between error flags and attack status.&quot;)</pre><pre>LLR p-value = 0.0000 &lt; 0.05<br>Decision: Reject H0.<br>Conclusion: Error flag and attack status are STATISTICALLY ASSOCIATED.</pre><h4>3.5 Influence of Urgent Packets</h4><pre>urgent_flag = (df1[&#39;urgent&#39;] &gt; 0).astype(int)<br>X = sm.add_constant(pd.DataFrame(urgent_flag))<br>y = df[&#39;attackflag&#39;]<br><br>model = sm.Logit(y, X)<br>result = model.fit()<br><br>print(result.summary())</pre><pre>Optimization terminated successfully.<br>         Current function value: 0.690751<br>         Iterations 4<br>                           Logit Regression Results                           <br>==============================================================================<br>Dep. Variable:             attackflag   No. Observations:               125973<br>Model:                          Logit   Df Residuals:                   125971<br>Method:                           MLE   Df Model:                            1<br>Date:                Sun, 28 Dec 2025   Pseudo R-squ.:               3.717e-06<br>Time:                        07:59:37   Log-Likelihood:                -87016.<br>converged:                       True   LL-Null:                       -87016.<br>Covariance Type:            nonrobust   LLR p-value:                    0.4212<br>==============================================================================<br>                 coef    std err          z      P&gt;|z|      [0.025      0.975]<br>------------------------------------------------------------------------------<br>const         -0.1385      0.006    -24.522      0.000      -0.150      -0.127<br>urgent        -0.5546      0.707     -0.784      0.433      -1.941       0.831<br>==============================================================================</pre><pre>beta = result.params[&#39;urgent&#39;]<br>p_two_sided = result.pvalues[&#39;urgent&#39;]<br><br>if beta &gt; 0:<br>    p_one_sided = p_two_sided / 2<br>else:<br>    p_one_sided = 1.0<br><br>alpha = 0.05<br><br>print(f&quot;β_urgent = {beta:.4f}&quot;)<br>print(f&quot;One-sided p-value = {p_one_sided:.4f}&quot;)<br><br>if p_one_sided &lt; alpha:<br>    print(&quot;Decision: Reject H0.&quot;)<br>    print(&quot;Conclusion:\nConnections with urgent packets have higher odds of being anomalous.&quot;)<br>else:<br>    print(&quot;Decision: Fail to reject H0.&quot;)<br>    print(&quot;Conclusion:\nInsufficient evidence that urgent packets increase the odds of an anomaly.&quot;)</pre><pre>β_urgent = -0.5546<br>One-sided p-value = 1.0000<br>Decision: Fail to reject H0.<br>Conclusion:<br>Insufficient evidence that urgent packets increase the odds of an anomaly.</pre><pre>odds_ratio = np.exp(beta)<br>print(f&quot;Odds ratio = {odds_ratio:.3f}&quot;)<br>if odds_ratio &gt; 1:<br>    print(f&#39;Connections with urgent packets have {odds_ratio:.2f}× higher odds of being anomalous.&#39;)<br>else:<br>    print(f&#39;Connections with urgent packets have {odds_ratio:.2f}× lower odds of being anomalous.&#39;)</pre><pre>Odds ratio = 0.574<br>Connections with urgent packets have 0.57× lower odds of being anomalous.</pre><p>Thus, Logistic regression provides no evidence that the presence of urgent packets increases the odds of an anomalous connection.</p><h3>4. Pre-processing the Data for Modelling</h3><h4>4.1 Creating pre-processing Pipelines</h4><pre>cat_cols = df.drop(columns=[&#39;attack&#39;,&#39;attackflag&#39;,&#39;attacktype&#39;]).select_dtypes(&#39;object&#39;).columns.to_list()<br>num_cols = df.drop(columns=[&#39;attack&#39;,&#39;attackflag&#39;,&#39;attacktype&#39;]).select_dtypes(exclude=&#39;object&#39;).columns.to_list()<br>num_nominal_cols = [col for col in num_cols if df[col].nunique()==2]<br>num_ordinal_cols = [col for col in num_cols if col not in num_nominal_cols]<br><br># Pipeline for Categorical Features<br>cat_pipeline = Pipeline([<br>    (&#39;ohe&#39;, OneHotEncoder(<br>        handle_unknown=&#39;infrequent_if_exist&#39;,<br>        min_frequency=0.01<br>    ))<br>])<br><br># Pipeline for numerical features and linear models (LogReg, SVC, etc.)<br>&#39;&#39;&#39;<br>Why? - Because Linear models work directly with numerical values, <br>so very large or highly skewed numbers can dominate their decisions <br>and reduce reliability; applying log transformation and scaling <br>brings all features to a comparable, stable range. <br>Tree-based models make decisions by comparing values step by step <br>rather than combining them mathematically, so they are naturally <br>unaffected by differences in scale or skewness.<br>&#39;&#39;&#39;<br><br>num_ordinal_pipeline_linear = Pipeline([<br>    (&#39;log&#39;, FunctionTransformer(np.log1p, feature_names_out=&#39;one-to-one&#39;)),<br>    (&#39;scale&#39;, StandardScaler())<br>])<br><br>preprocess_linear = ColumnTransformer([<br>    (&#39;cat&#39;, cat_pipeline, cat_cols),<br>    (&#39;num_ordinal&#39;, num_ordinal_pipeline_linear, num_ordinal_cols)<br>])<br><br>preprocess_tree = ColumnTransformer([<br>    (&#39;cat&#39;, cat_pipeline, cat_cols)<br>])</pre><h4>4.2 Train-Test Split</h4><p>We will essentially train two separate pipelines. The first pipeline is trained on full data, with target being y_bin i.e. binary classification task of Normal (0) vs Attack (1). The Second pipeline is trained on only the attack data, with target being y_multi, which is a multiclass classification task for detecting Attack Type.</p><pre>X = df.drop(columns=[&#39;attack&#39;,&#39;attackflag&#39;,&#39;attacktype&#39;])<br>y_bin = df[&#39;attackflag&#39;]<br>y_multi = df[&#39;attacktype&#39;]<br><br>X_train_bin, <br>X_test_bin, <br>y_train_bin, <br>y_test_bin, <br>y_train_multi_with_normals, <br>y_test_multi_with_normals = train_test_split(X,<br>                                             y_bin,<br>                                             y_multi,<br>                                             test_size=0.2,<br>                                             stratify=y_bin,<br>                                             random_state=42)<br><br>attacks_only_mask_train = y_train_bin == 1<br><br>X_train_multi = X_train_bin[attacks_only_mask_train]<br>y_train_multi = y_train_multi_with_normals[attacks_only_mask_train]<br><br>attacks_only_mask_test = y_test_bin == 1<br><br>X_test_multi = X_test_bin[attacks_only_mask_test]<br>y_test_multi = y_test_multi_with_normals[attacks_only_mask_test]</pre><h3>5. Modelling — Binary Classification (Normal vs. Attack)</h3><h4>5.1 Defining Models</h4><pre>models_bin = {<br><br>    &#39;logistic&#39;: Pipeline([<br>        (&#39;preprocess&#39;, preprocess_linear),<br>        (&#39;clf&#39;, LogisticRegression(<br>            max_iter=1000,<br>            class_weight=&#39;balanced&#39;,<br>            random_state=42,<br>            verbose=True,<br>            n_jobs=-1<br>        ))<br>    ]),<br><br>    &#39;linear_svc&#39;: Pipeline([<br>        (&#39;preprocess&#39;, preprocess_linear),<br>        (&#39;clf&#39;, LinearSVC(<br>            class_weight=&#39;balanced&#39;,<br>            random_state=42,<br>            verbose=True<br>        ))<br>    ]),<br><br>    &#39;rf&#39;:Pipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;clf&#39;, RandomForestClassifier(<br>            class_weight=&#39;balanced&#39;,<br>            random_state=42,<br>            n_jobs=-1,<br>            verbose=True<br>        ))<br>    ]),<br><br>    &#39;adaboost&#39;:Pipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;clf&#39;, AdaBoostClassifier(<br>            estimator=DecisionTreeClassifier(),<br>            random_state=42<br>        ))<br>    ]),<br><br>    &#39;gradboost&#39;:Pipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;clf&#39;, GradientBoostingClassifier(<br>            n_estimators=500,<br>            n_iter_no_change=10,<br>            random_state=42,<br>            verbose=True<br>        ))<br>    ]),<br>    <br>    &#39;stacking&#39;:Pipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;clf&#39;, StackingClassifier(<br>            estimators=[<br>                (<br>                    &#39;linear_svm&#39;, <br>                    LinearSVC(<br>                            class_weight=&#39;balanced&#39;,<br>                            random_state=42,<br>                            verbose=True<br>                    )<br>                ),<br>                (<br>                    &#39;rf&#39;, <br>                    RandomForestClassifier(<br>                        n_estimators=300,<br>                        random_state=42,<br>                        n_jobs=-1,<br>                        verbose=True<br>                    )<br>                )<br>            ],<br>            final_estimator=LogisticRegression(max_iter=1000,<br>                                               random_state=42,<br>                                               n_jobs=-1,<br>                                               verbose=True),<br>            cv=5,<br>            n_jobs=-1,<br>            verbose=True<br>        ))<br>    ])<br>}</pre><h4>5.2 Defining Distribution Grids for Randomized Search Cross Validation (RSCV)</h4><pre>logreg_dist_bin = {<br>    &#39;clf__C&#39;: stats.loguniform(1e-3, 1e2),<br>}<br><br>linear_svc_dist_bin = {<br>    &#39;clf__C&#39;: stats.loguniform(1e-3, 1e2)<br>}<br><br>rf_dist_bin = {<br>    &#39;clf__n_estimators&#39;: stats.randint(100, 500),<br>    &#39;clf__max_depth&#39;: [10, 20, 30],<br>    &#39;clf__min_samples_split&#39;: stats.randint(2, 20),<br>    &#39;clf__min_samples_leaf&#39;: stats.randint(1, 10),<br>    &#39;clf__max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;]<br>}<br><br>adaboost_dist_bin = {<br>    &#39;clf__n_estimators&#39;: stats.randint(100, 500),<br>    &#39;clf__learning_rate&#39;: stats.loguniform(1e-3, 1),<br>    &#39;clf__estimator__max_depth&#39;: [1, 2, 3]<br>}<br><br>gradboost_dist_bin = {<br>    &#39;clf__max_depth&#39;: stats.randint(2, 6),<br>    &#39;clf__learning_rate&#39;: stats.loguniform(1e-3, 1),<br>    &#39;clf__subsample&#39;: stats.uniform(0.6, 0.4)<br>}<br><br>stacking_dist_bin = {<br>    &#39;clf__final_estimator__C&#39;: stats.loguniform(1e-3, 1e2)<br>}<br><br>param_dists_bin = {<br>    &#39;logistic&#39;: logreg_dist_bin,<br>    &#39;linear_svc&#39;: linear_svc_dist_bin,<br>    &#39;rf&#39;: rf_dist_bin,<br>    &#39;adaboost&#39;: adaboost_dist_bin,<br>    &#39;gradboost&#39;: gradboost_dist_bin,<br>    &#39;stacking&#39;: stacking_dist_bin<br>}</pre><h4>5.3 Defining Cross Validation and Scoring Functions</h4><pre>skf = StratifiedKFold(<br>    n_splits=5,<br>    shuffle=True,<br>    random_state=42<br>)<br><br>scoring = {<br>    &#39;accuracy&#39;:&#39;accuracy&#39;,<br>    &#39;precision&#39;:&#39;precision&#39;,<br>    &#39;recall&#39;:&#39;recall&#39;,<br>    &#39;f1&#39;:&#39;f1&#39;<br>}</pre><h4>5.4 RSCV</h4><pre>results_bin = {}<br><br>print(&#39;=&#39;*100)<br>t = &#39;RANDOMIZED SEARCH CV FOR BINARY CLASSIFICATION&#39;<br>print(&#39; &#39;*int((100-len(t))/2),t,&#39; &#39;*int((100-len(t))/2))<br>print(&#39;=&#39;*100)<br><br>for name, model in models_bin.items():<br>    print(&#39;\n&#39;)<br>    print(f&quot;Running RSCV for {name.upper()}...&quot;)<br>    rs = RandomizedSearchCV(<br>    estimator=model,<br>    param_distributions=param_dists_bin[name],<br>    n_iter=20,<br>    cv=skf,<br>    scoring=scoring,   <br>    refit=&#39;f1&#39;,<br>    n_jobs=-1,<br>    random_state=42,<br>    verbose=3<br>    )<br>    <br>    rs.fit(X_train_bin, y_train_bin)<br>    <br>    results_bin[name] = {<br>    &#39;best_estimator&#39;: rs.best_estimator_,<br>    &#39;best_score&#39;: rs.best_score_,<br>    &#39;best_params&#39;: rs.best_params_,<br>    &#39;cv_results&#39;: {<br>        k: rs.cv_results_[k].mean()<br>        for k in rs.cv_results_<br>        if k.startswith(&#39;mean_test_&#39;)<br>    }}<br>    print(&#39;\n&#39;)<br>    print(&#39;-&#39;*100)</pre><pre>====================================================================================================<br>                            RANDOMIZED SEARCH CV FOR BINARY CLASSIFICATION                            <br>====================================================================================================<br><br><br>Running RSCV for LOGISTIC...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br>[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers.<br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for LINEAR_SVC...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br>[LibLinear]<br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for RF...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br>[Parallel(n_jobs=-1)]: Using backend ThreadingBackend with 8 concurrent workers.<br>[Parallel(n_jobs=-1)]: Done  34 tasks      | elapsed:    0.5s<br>[Parallel(n_jobs=-1)]: Done 184 tasks      | elapsed:    2.6s<br>[Parallel(n_jobs=-1)]: Done 330 out of 330 | elapsed:    4.8s finished<br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for ADABOOST...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for GRADBOOST...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br>      Iter       Train Loss      OOB Improve   Remaining Time <br>         1           0.6102           0.7769           33.27s<br>         2           0.4059           0.1921           29.65s<br>         3           0.3320           0.0821           31.78s<br>         4           0.2961           0.0345           31.95s<br>         5           0.2793           0.0169           29.49s<br>         6           0.2671           0.0121           27.55s<br>         7           0.2583           0.0044           26.06s<br>         8           0.2522           0.0064           26.77s<br>         9           0.2484          -0.0025           26.84s<br>        10           0.2511           0.0118           27.59s<br>        20           0.2472           0.0050           24.61s<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for STACKING...<br>Fitting 5 folds for each of 20 candidates, totalling 100 fits<br>[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers.<br><br>----------------------------------------------------------------------------------------------------</pre><pre>print(&#39;=&#39;*100)<br>t = &#39;BINARY CLASSIFICATION RESULTS&#39;<br>print(&#39; &#39;*int((100-len(t))/2),t,&#39; &#39;*int((100-len(t))/2))<br>print(&#39;=&#39;*100)<br><br>for name, scores in results_bin.items():<br>    print(&#39;\n&#39;)<br>    print(f&quot;{name.upper()}:&quot;)<br>    print(&#39;\t&#39;, &#39;Best F1 Score =&#39;, round(scores[&#39;best_score&#39;],4))<br>    print(&#39;\t&#39;, &#39;Best Params:&#39;)<br>    for param, value in scores[&#39;best_params&#39;].items():<br>        if isinstance(value, (int, float)):<br>            value = round(value,4)<br>        print(&#39;\t\t&#39;, param, &#39;:&#39;, value)<br>    print(&#39;\t&#39;, &#39;CV Results:&#39;)<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Accuracy = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_accuracy&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation F1 Score = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_f1&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Recall = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_recall&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Precision = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_precision&#39;],4))<br>    print(&#39;\n&#39;)<br>    print(&#39;-&#39;*100)</pre><pre>====================================================================================================<br>                                    BINARY CLASSIFICATION RESULTS                                    <br>====================================================================================================<br><br><br>LOGISTIC:<br>  Best F1 Score = 0.9782<br>  Best Params:<br>   clf__C : 14.5282<br>  CV Results:<br>   Mean Validation Accuracy =  0.9748<br>   Mean Validation F1 Score =  0.9729<br>   Mean Validation Recall =  0.9717<br>   Mean Validation Precision =  0.9741<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>LINEAR_SVC:<br>  Best F1 Score = 0.9767<br>  Best Params:<br>   clf__C : 4.5706<br>  CV Results:<br>   Mean Validation Accuracy =  0.9774<br>   Mean Validation F1 Score =  0.9757<br>   Mean Validation Recall =  0.9746<br>   Mean Validation Precision =  0.9769<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>RF:<br>  Best F1 Score = 0.9585<br>  Best Params:<br>   clf__max_depth : 30<br>   clf__max_features : sqrt<br>   clf__min_samples_leaf : 1<br>   clf__min_samples_split : 6<br>   clf__n_estimators : 330<br>  CV Results:<br>   Mean Validation Accuracy =  0.9613<br>   Mean Validation F1 Score =  0.9584<br>   Mean Validation Recall =  0.9581<br>   Mean Validation Precision =  0.9587<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>ADABOOST:<br>  Best F1 Score = 0.9577<br>  Best Params:<br>   clf__estimator__max_depth : 2<br>   clf__learning_rate : 0.7025<br>   clf__n_estimators : 415<br>  CV Results:<br>   Mean Validation Accuracy =  0.9471<br>   Mean Validation F1 Score =  0.9418<br>   Mean Validation Recall =  0.9296<br>   Mean Validation Precision =  0.9557<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>GRADBOOST:<br>  Best F1 Score = 0.9585<br>  Best Params:<br>   clf__learning_rate : 0.6541<br>   clf__max_depth : 3<br>   clf__subsample : 0.6727<br>  CV Results:<br>   Mean Validation Accuracy =  0.956<br>   Mean Validation F1 Score =  0.9523<br>   Mean Validation Recall =  0.9461<br>   Mean Validation Precision =  0.9589<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>STACKING:<br>  Best F1 Score = 0.9586<br>  Best Params:<br>   clf__final_estimator__C : 0.0746<br>  CV Results:<br>   Mean Validation Accuracy =  0.9613<br>   Mean Validation F1 Score =  0.9584<br>   Mean Validation Recall =  0.9576<br>   Mean Validation Precision =  0.9592<br><br><br>----------------------------------------------------------------------------------------------------</pre><p><strong>Best Model: Logistic Regressor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*7iVFI-nDcgwvXo5Wzxylqw.png" /></figure><h4>5.5 Performance of Best Model on Test Data</h4><pre>y_test_bin_pred = best_model_bin.predict(X_test_bin)<br><br>print(classification_report(<br>    y_test_bin,<br>    y_test_bin_pred,<br>    target_names=[&quot;Normal&quot;, &quot;Attack&quot;]<br>))<br><br>y_test_bin_proba = best_model_bin.predict_proba(X_test_bin)[:, 1]<br>roc_auc = roc_auc_score(y_test_bin, y_test_bin_proba)<br>print(&quot;ROC-AUC:&quot;, round(roc_auc,4))<br><br>cm = confusion_matrix(y_test_bin, y_test_bin_pred)<br><br>ConfusionMatrixDisplay(<br>    confusion_matrix=cm,<br>    display_labels=[&quot;Normal&quot;, &quot;Attack&quot;],<br>).plot(values_format=&#39;d&#39;)<br><br>plt.show()</pre><pre>precision    recall  f1-score   support<br><br>      Normal       0.98      0.98      0.98     13469<br>      Attack       0.98      0.98      0.98     11726<br><br>    accuracy                           0.98     25195<br>   macro avg       0.98      0.98      0.98     25195<br>weighted avg       0.98      0.98      0.98     25195<br><br>ROC-AUC: 0.9969</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw59jexuefj-4UYB8gLOcw.png" /></figure><h4>5.6 Feature Importances</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvSorhFwJRB1S5ivgZBD_g.png" /></figure><p><strong>— Features with Strong Positive Coefficients (&gt;1), indicating increased likelihood of an ATTACK:</strong></p><ul><li>Basic Connection Features: flag_RSTR, flag_S0, flag_SF, service_eco_i, service_ecr_i, service_private</li><li>Content-Related Features: hot</li><li>Time-Related Traffic Features: count, srvrerrorrate, srvserrorrate</li><li>Host-based Traffic Features: dsthostrerrorrate, dsthostsamesrcportrate, dsthostsrvserrorrate</li></ul><p><strong>— Features with Strong Negative Coefficients (&lt;-1), indicating increased likelihood of a NORMAL ACTIVITY:</strong></p><ul><li>Basic Connection Features: flag_REJ, flag_infrequent_sklearn, protocoltype_icmp, service_domain_u, service_ftp, service_other, service_telnet</li><li>Time-Related Traffic Features: serrorrate</li><li>Host-based Traffic Features: dsthostsrvcount</li></ul><h4>5.7 Saving the Best Model</h4><pre>dump(best_model_bin, &#39;../artifacts/binary_model.joblib&#39;)</pre><h3>6. Modelling — Multiclass classification (Attack Type — DoS/Probe/R2L/U2R)</h3><h4>6.1 Defining Models</h4><p>Let us check the value counts for the multiclass target i.e. attack type:</p><pre>y_train_multi.value_counts()</pre><pre>attacktype<br>DoS      36822<br>Probe     9267<br>R2L        769<br>U2R         46<br>Name: count, dtype: int64</pre><p>We can see that the class imbalance for R2L and U2R classes is very high. To mitigate this, we will use SMOTE Over-sampling.</p><pre>smote = SMOTE(sampling_strategy={&#39;R2L&#39;:2000, &#39;U2R&#39;:500}, random_state=42)<br><br>models_multi = {<br><br>    &#39;logistic_ovr&#39;: ImbPipeline([<br>        (&#39;preprocess&#39;, preprocess_linear),<br>        (&#39;smote&#39;, smote),<br>        (&#39;clf&#39;, LogisticRegression(<br>            max_iter=2000,<br>            multi_class=&#39;ovr&#39;,<br>            class_weight=&#39;balanced&#39;,<br>            n_jobs=-1,<br>            random_state=42<br>        ))<br>    ]),<br><br>    &#39;linear_svc_ovr&#39;: ImbPipeline([<br>        (&#39;preprocess&#39;, preprocess_linear),<br>        (&#39;smote&#39;, smote),<br>        (&#39;clf&#39;, LinearSVC(<br>            class_weight=&#39;balanced&#39;,<br>            random_state=42<br>        ))<br>    ]),<br><br>    &#39;rf&#39;: ImbPipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;smote&#39;, smote),<br>        (&#39;clf&#39;, RandomForestClassifier(<br>            class_weight=&#39;balanced&#39;,<br>            n_jobs=-1,<br>            random_state=42<br>        ))<br>    ]),<br><br>    &#39;adaboost&#39;: ImbPipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;smote&#39;, smote),<br>        (&#39;clf&#39;, AdaBoostClassifier(<br>            estimator=DecisionTreeClassifier(),<br>            random_state=42<br>        ))<br>    ]),<br><br>    &#39;gradboost&#39;: ImbPipeline([<br>        (&#39;preprocess&#39;, preprocess_tree),<br>        (&#39;smote&#39;, smote),<br>        (&#39;clf&#39;, GradientBoostingClassifier(<br>            n_estimators=500,<br>            n_iter_no_change=10,<br>            random_state=42<br>        ))<br>    ])<br>}</pre><h4>6.2 Defining Distribution Grids for Randomized Search Cross Validation (RSCV)</h4><pre>logreg_dist_multi = {<br>    &#39;clf__C&#39;: stats.loguniform(1e-3, 1e2)<br>}<br><br>linearsvc_dist_multi = {<br>    &#39;clf__C&#39;: stats.loguniform(1e-3, 1e2)<br>}<br><br>rf_dist_multi = {<br>    &#39;clf__n_estimators&#39;: stats.randint(100, 500),<br>    &#39;clf__max_depth&#39;: [10, 20, 30],<br>    &#39;clf__min_samples_split&#39;: stats.randint(2, 20),<br>    &#39;clf__min_samples_leaf&#39;: stats.randint(1, 10),<br>    &#39;clf__max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;]<br>}<br><br>adaboost_dist_multi = {<br>    &#39;clf__n_estimators&#39;: stats.randint(100, 500),<br>    &#39;clf__learning_rate&#39;: stats.loguniform(1e-3, 1),<br>    &#39;clf__estimator__max_depth&#39;: [1, 2, 3]<br>}<br><br>gradboost_dist_multi = {<br>    &#39;clf__max_depth&#39;: stats.randint(2, 6),<br>    &#39;clf__learning_rate&#39;: stats.loguniform(1e-3, 1),<br>    &#39;clf__subsample&#39;: stats.uniform(0.6, 0.4)<br>}<br><br>param_dists_multi = {<br>    &#39;logistic_ovr&#39;: logreg_dist_multi,<br>    &#39;linear_svc_ovr&#39;: linearsvc_dist_multi,<br>    &#39;rf&#39;: rf_dist_multi,<br>    &#39;adaboost&#39;: adaboost_dist_multi,<br>    &#39;gradboost&#39;: gradboost_dist_multi<br>}</pre><h4>6.3 Defining Cross Validation and Scoring Functions</h4><pre>skf = StratifiedKFold(<br>    n_splits=5,<br>    shuffle=True,<br>    random_state=42<br>)<br><br>scoring_multi = {<br>    &#39;accuracy&#39;: &#39;accuracy&#39;,<br>    &#39;f1&#39;: &#39;f1_macro&#39;,<br>    &#39;precision&#39;: &#39;precision_macro&#39;,<br>    &#39;recall&#39;: &#39;recall_macro&#39;<br>}</pre><h4>6.4 RSCV</h4><pre>results_multi = {}<br><br>print(&#39;=&#39;*100)<br>t = &#39;RANDOMIZED SEARCH CV FOR MULTICLASS CLASSIFICATION&#39;<br>print(&#39; &#39;*int((100-len(t))/2),t,&#39; &#39;*int((100-len(t))/2))<br>print(&#39;=&#39;*100)<br><br>for name, model in models_multi.items():<br>    print(&#39;\n&#39;)<br>    print(f&quot;Running RSCV for {name.upper()}...&quot;)<br>    rs = RandomizedSearchCV(<br>        estimator=model,<br>        param_distributions=param_dists_multi[name],<br>        n_iter=10,<br>        cv=skf,<br>        scoring=scoring_multi,<br>        refit=&#39;f1&#39;,<br>        n_jobs=1,<br>        random_state=42,<br>        verbose=1<br>        )<br>    <br>    rs.fit(X_train_multi, y_train_multi)<br>    <br>    results_multi[name] = {<br>    &#39;best_estimator&#39;: rs.best_estimator_,<br>    &#39;best_score&#39;: rs.best_score_,<br>    &#39;best_params&#39;: rs.best_params_,<br>    &#39;cv_results&#39;: {<br>        k: rs.cv_results_[k].mean()<br>        for k in rs.cv_results_<br>        if k.startswith(&#39;mean_test_&#39;)<br>    }}<br>    print(&#39;\n&#39;)<br>    print(&#39;-&#39;*100)</pre><pre>====================================================================================================<br>                          RANDOMIZED SEARCH CV FOR MULTICLASS CLASSIFICATION                          <br>====================================================================================================<br><br><br>Running RSCV for LOGISTIC_OVR...<br>Fitting 5 folds for each of 10 candidates, totalling 50 fits<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for LINEAR_SVC_OVR...<br>Fitting 5 folds for each of 10 candidates, totalling 50 fits<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for RF...<br>Fitting 5 folds for each of 10 candidates, totalling 50 fits<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for ADABOOST...<br>Fitting 5 folds for each of 10 candidates, totalling 50 fits<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>Running RSCV for GRADBOOST...<br>Fitting 5 folds for each of 10 candidates, totalling 50 fits<br><br><br>----------------------------------------------------------------------------------------------------</pre><pre>print(&#39;=&#39;*100)<br>t = &#39;MULTICLASS CLASSIFICATION RESULTS&#39;<br>print(&#39; &#39;*int((100-len(t))/2),t,&#39; &#39;*int((100-len(t))/2))<br>print(&#39;=&#39;*100)<br><br>for name, scores in results_multi.items():<br>    print(&#39;\n&#39;)<br>    print(f&quot;{name.upper()}:&quot;)<br>    # print(&#39;\t&#39;, scores[&#39;best_estimator&#39;])<br>    print(&#39;\t&#39;, &#39;Best F1 Score =&#39;, round(scores[&#39;best_score&#39;],4))<br>    print(&#39;\t&#39;, &#39;Best Params:&#39;)<br>    for param, value in scores[&#39;best_params&#39;].items():<br>        if isinstance(value, (int, float)):<br>            value = round(value,4)<br>        print(&#39;\t\t&#39;, param, &#39;:&#39;, value)<br>    print(&#39;\t&#39;, &#39;CV Results:&#39;)<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Accuracy = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_accuracy&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation F1 Score = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_f1&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Recall = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_recall&#39;],4))<br>    print(&#39;\t\t&#39;, &#39;Mean Validation Precision = &#39;, round(scores[&#39;cv_results&#39;][&#39;mean_test_precision&#39;],4))<br>    print(&#39;\n&#39;)<br>    print(&#39;-&#39;*100)</pre><pre>====================================================================================================<br>                            MULTICLASS CLASSIFICATION RESULTS                                  <br>====================================================================================================<br><br><br>LOGISTIC_OVR:<br>	 Best F1 Score = 0.9217<br>	 Best Params:<br>		 clf__C : 56.6985<br>	 CV Results:<br>		 Mean Validation Accuracy =  0.9945<br>		 Mean Validation F1 Score =  0.8967<br>		 Mean Validation Recall =  0.9585<br>		 Mean Validation Precision =  0.8654<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>LINEAR_SVC_OVR:<br>	 Best F1 Score = 0.931<br>	 Best Params:<br>		 clf__C : 0.9847<br>	 CV Results:<br>		 Mean Validation Accuracy =  0.9969<br>		 Mean Validation F1 Score =  0.9166<br>		 Mean Validation Recall =  0.9508<br>		 Mean Validation Precision =  0.8995<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>RF:<br>	 Best F1 Score = 0.8006<br>	 Best Params:<br>		 clf__max_depth : 30<br>		 clf__max_features : log2<br>		 clf__min_samples_leaf : 5<br>		 clf__min_samples_split : 3<br>		 clf__n_estimators : 443<br>	 CV Results:<br>		 Mean Validation Accuracy =  0.9308<br>		 Mean Validation F1 Score =  0.7912<br>		 Mean Validation Recall =  0.8759<br>		 Mean Validation Precision =  0.7584<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>ADABOOST:<br>	 Best F1 Score = 0.8528<br>	 Best Params:<br>		 clf__estimator__max_depth : 3<br>		 clf__learning_rate : 0.2183<br>		 clf__n_estimators : 120<br>	 CV Results:<br>		 Mean Validation Accuracy =  0.9077<br>		 Mean Validation F1 Score =  0.7252<br>		 Mean Validation Recall =  0.7041<br>		 Mean Validation Precision =  0.78<br><br><br>----------------------------------------------------------------------------------------------------<br><br><br>GRADBOOST:<br>	 Best F1 Score = 0.8536<br>	 Best Params:<br>		 clf__learning_rate : 0.0133<br>		 clf__max_depth : 2<br>		 clf__subsample : 0.6734<br>	 CV Results:<br>		 Mean Validation Accuracy =  0.9277<br>		 Mean Validation F1 Score =  0.7414<br>		 Mean Validation Recall =  0.7446<br>		 Mean Validation Precision =  0.7784</pre><p><strong>Best Model: Linear SVC</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*oNPkNu8-BGEGbq-7w9bh3A.png" /></figure><h4>6.5 Performance of Best Model on Test Data</h4><pre>y_test_multi_pred = best_model_multi.predict(X_test_multi)<br><br>print(classification_report(<br>    y_test_multi,<br>    y_test_multi_pred<br>))<br><br>cm = confusion_matrix(y_test_multi, y_test_multi_pred)<br><br>ConfusionMatrixDisplay(<br>    confusion_matrix=cm,<br>    display_labels=np.unique(y_test_multi)<br>).plot(values_format=&#39;d&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*qq9EdnRl9nqQzASIsVg7JA.png" /></figure><ul><li><strong>DoS and Probe achieve near-perfect precision, recall, and F1-score</strong> with very large support, indicating extremely reliable detection.</li><li>R2L shows slightly lower recall (0.96), meaning some R2L attacks are missed, but overall performance remains high.</li><li>U2R has perfect recall but very low precision (0.43), indicating many false positives despite detecting all true U2R samples.</li><li>Macro averages are noticeably lower than weighted averages, highlighting the impact of severe class imbalance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8if5VGZvSXwekQtfIw9zw.png" /></figure><ul><li><strong>DoS is classified with extremely high accuracy,</strong> with only 15 misclassifications out of 9,105 total DoS samples.</li><li>Probe shows strong performance, but minor confusion exists with R2L and U2R, indicating some overlap in attack behavior.</li><li>R2L has the weakest performance relative to its size, with noticeable misclassification into U2R and Probe.</li><li><strong>U2R has perfect precision in this matrix, but the very small sample size (6) limits confidence in robustness.</strong></li><li><strong>Overall errors are rare and mostly occur between Probe, R2L, and U2R, suggesting these classes are harder to separate.</strong></li><li>The confusion matrix is highly imbalanced, so accuracy alone may be misleading without recall and F1-score analysis.</li></ul><h4>6.6 Feature Importances</h4><p>We get the feature importances for each attack type using the following function:</p><pre># First we get the feature names <br>ct = best_model_multi.named_steps[&#39;preprocess&#39;]<br>ohe = ct.named_transformers_[&#39;cat&#39;].named_steps[&#39;ohe&#39;]<br>cat_input_features = ct.transformers_[0][2]<br>cat_feature_names = ohe.get_feature_names_out(cat_input_features)<br>num_feature_names = ct.transformers_[1][2]<br>feature_names = list(cat_feature_names) + list(num_feature_names)<br><br># Function to plot feature importances<br>def feature_imp(attack, COEF_THRESHOLD=0):<br>    clf = best_model_multi.named_steps[&#39;clf&#39;]<br>    class_idx = list(clf.classes_).index(attack)<br>    coefs = clf.coef_[class_idx]<br><br>    imp = (<br>        pd.DataFrame({<br>            &quot;feature&quot;: feature_names,<br>            &quot;coef&quot;: coefs<br>        })<br>        .sort_values(&quot;coef&quot;, ascending=True)<br>    )<br><br>    plt.figure(figsize=(6, 10))<br>    plt.barh(imp[&quot;feature&quot;], imp[&quot;coef&quot;])<br>    plt.xlabel(&quot;Coefficient value&quot;)<br>    plt.title(f&quot;Top feature importances for {attack} (Multiclass Classification)&quot;)<br>    plt.tight_layout()<br>    plt.show()</pre><h4>6.6.1 DoS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT7Q8Ft19J4cP6OotuxBeQ.png" /></figure><h4>6.6.2 Probe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JcRSmctltQDL3Z1B77fXg.png" /></figure><h4>6.6.3 R2L</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdCV6iZiH3CApmTpj8j-nA.png" /></figure><h4>6.6.4 U2R</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hn6kzigzWmJY7mNMMsIbig.png" /></figure><h4>6.7 Saving the Best Model</h4><pre>dump(deploy_pipeline, &quot;../artifacts/multiclass_model.joblib&quot;)</pre><h3>7. Deployment</h3><p>The trained intrusion detection system is deployed as a lightweight REST API using Flask (<strong>app.py)</strong>. The deployment design mirrors the modeling strategy used during training: a <strong>two-stage hierarchical classifier</strong>, where binary detection is performed first, followed by attack-type identification only when malicious traffic is detected.</p><pre>from flask import Flask, request, jsonify<br>import joblib<br>import pandas as pd<br><br>BIN_MODEL_PATH = &quot;artifacts/binary_model.joblib&quot;<br>MULTI_MODEL_PATH = &quot;artifacts/multiclass_model.joblib&quot;<br><br>bin_model = joblib.load(BIN_MODEL_PATH)<br>multi_model = joblib.load(MULTI_MODEL_PATH)<br><br>def predict_single(record: dict):<br>    &quot;&quot;&quot;<br>    record: dict of raw feature values<br>    &quot;&quot;&quot;<br>    X = pd.DataFrame([record])<br><br>    attack_pred = bin_model.predict(X)[0]<br>    attack_prob = bin_model.predict_proba(X)[0, 1]<br><br>    if attack_pred == 0:<br>        return {<br>            &quot;prediction&quot;: &quot;normal&quot;,<br>            &quot;attack_probability&quot;: float(attack_prob)<br>        }<br><br>    attack_type = multi_model.predict(X)[0]<br><br>    return {<br>        &quot;prediction&quot;: &quot;attack&quot;,<br>        &quot;attack_type&quot;: attack_type,<br>        &quot;attack_probability&quot;: float(attack_prob)<br>    }<br><br>app = Flask(__name__)<br><br>@app.route(&quot;/&quot;, methods=[&quot;GET&quot;])<br>def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br><br>@app.route(&quot;/predict&quot;, methods=[&quot;POST&quot;])<br>def predict():<br>    data = request.get_json()<br><br>    if data is None:<br>        return jsonify({&quot;error&quot;: &quot;Invalid JSON&quot;}), 400<br><br>    try:<br>        result = predict_single(data)<br>        return jsonify(result)<br>    except Exception as e:<br>        return jsonify({&quot;error&quot;: str(e)}), 500<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=5000, debug=True)</pre><h4>Binary Prediction and Attack Probability</h4><p>The first stage of inference uses the binary<strong> Logistic Regression classifier</strong> to predict whether the connection is an attack. Along with the predicted class, the model also outputs an <strong>attack probability</strong>, which represents the likelihood of malicious behavior.</p><p>If the connection is classified as normal, the request terminates early. Let us understand this with a test case of normal connection.</p><pre>// NORMAL<br>{<br>    &quot;duration&quot;: 0,<br>    &quot;protocoltype&quot;: &quot;tcp&quot;,<br>    &quot;service&quot;: &quot;http&quot;,<br>    &quot;flag&quot;: &quot;SF&quot;,<br>    &quot;srcbytes&quot;: 181,<br>    &quot;dstbytes&quot;: 5450,<br>    &quot;land&quot;: 0,<br>    &quot;wrongfragment&quot;: 0,<br>    &quot;urgent&quot;: 0,<br>    &quot;hot&quot;: 0,<br>    &quot;numfailedlogins&quot;: 0,<br>    &quot;loggedin&quot;: 1,<br>    &quot;numcompromised&quot;: 0,<br>    &quot;rootshell&quot;: 0,<br>    &quot;suattempted&quot;: 0,<br>    &quot;numroot&quot;: 0,<br>    &quot;numfilecreations&quot;: 0,<br>    &quot;numshells&quot;: 0,<br>    &quot;numaccessfiles&quot;: 0,<br>    &quot;numoutboundcmds&quot;: 0,<br>    &quot;ishostlogin&quot;: 0,<br>    &quot;isguestlogin&quot;: 0,<br>    &quot;count&quot;: 2,<br>    &quot;srvcount&quot;: 2,<br>    &quot;serrorrate&quot;: 0.0,<br>    &quot;srvserrorrate&quot;: 0.0,<br>    &quot;rerrorrate&quot;: 0.0,<br>    &quot;srvrerrorrate&quot;: 0.0,<br>    &quot;samesrvrate&quot;: 1.0,<br>    &quot;diffsrvrate&quot;: 0.0,<br>    &quot;srvdiffhostrate&quot;: 0.0,<br>    &quot;dsthostcount&quot;: 9,<br>    &quot;dsthostsrvcount&quot;: 9,<br>    &quot;dsthostsamesrvrate&quot;: 1.0,<br>    &quot;dsthostdiffsrvrate&quot;: 0.0,<br>    &quot;dsthostsamesrcportrate&quot;: 0,<br>    &quot;dsthostsamedstportrate&quot;: 1.0,<br>    &quot;dsthostsrvdiffhostrate&quot;: 0.0,<br>    &quot;dsthostserrorrate&quot;: 0.0,<br>    &quot;dsthostsrvserrorrate&quot;: 0.0,<br>    &quot;dsthostrerrorrate&quot;: 0.0,<br>    &quot;dsthostsrvrerrorrate&quot;: 0.0<br>}</pre><p>This test case gives the following result in <strong>POSTMAN:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*9ma1gqAbMQX6ygeQP-5wLg.png" /></figure><p>Thus, the connection is successfully classified as <strong>NORMAL.</strong></p><h4>Multiclass Prediction and Confidence Estimation</h4><p>When a connection is classified as malicious, the system invokes the multiclass model to determine the specific attack type (DoS, Probe, R2L, or U2R).</p><p>The selected multiclass model is a <strong>Linear Support Vector Classifier</strong>, which does not natively support probability estimation. Instead of presenting misleading or artificially constructed probabilities, the deployment exposes <strong>normalized decision-function scores</strong> as <em>relative confidence values</em>.</p><p>These confidence scores reflect how strongly the model favors one attack type over others, rather than absolute likelihoods. While they are not true probabilities, they are valuable for interpretability and operational awareness.</p><p>To maintain transparency, the API explicitly labels these values as confidence scores rather than probabilities.</p><p>Let us understand this with an example test case of a DoS attacked connection.</p><pre>{<br>    &quot;duration&quot;: 0,<br>    &quot;protocoltype&quot;: &quot;tcp&quot;,<br>    &quot;service&quot;: &quot;private&quot;,<br>    &quot;flag&quot;: &quot;S0&quot;,<br>    &quot;srcbytes&quot;: 0,<br>    &quot;dstbytes&quot;: 0,<br>    &quot;land&quot;: 0,<br>    &quot;wrongfragment&quot;: 0,<br>    &quot;urgent&quot;: 0,<br>    &quot;hot&quot;: 0,<br>    &quot;numfailedlogins&quot;: 0,<br>    &quot;loggedin&quot;: 0,<br>    &quot;numcompromised&quot;: 0,<br>    &quot;rootshell&quot;: 0,<br>    &quot;suattempted&quot;: 0,<br>    &quot;numroot&quot;: 0,<br>    &quot;numfilecreations&quot;: 0,<br>    &quot;numshells&quot;: 0,<br>    &quot;numaccessfiles&quot;: 0,<br>    &quot;numoutboundcmds&quot;: 0,<br>    &quot;ishostlogin&quot;: 0,<br>    &quot;isguestlogin&quot;: 0,<br>    &quot;count&quot;: 123,<br>    &quot;srvcount&quot;: 6,<br>    &quot;serrorrate&quot;: 1,<br>    &quot;srvserrorrate&quot;: 1,<br>    &quot;rerrorrate&quot;: 0,<br>    &quot;srvrerrorrate&quot;: 0,<br>    &quot;samesrvrate&quot;: 0.05,<br>    &quot;diffsrvrate&quot;: 0.07,<br>    &quot;srvdiffhostrate&quot;: 0,<br>    &quot;dsthostcount&quot;: 255,<br>    &quot;dsthostsrvcount&quot;: 26,<br>    &quot;dsthostsamesrvrate&quot;: 0.1,<br>    &quot;dsthostdiffsrvrate&quot;: 0.05,<br>    &quot;dsthostsamesrcportrate&quot;: 0,<br>    &quot;dsthostsrvdiffhostrate&quot;: 0,<br>    &quot;dsthostserrorrate&quot;: 1,<br>    &quot;dsthostsrvserrorrate&quot;: 1,<br>    &quot;dsthostrerrorrate&quot;: 0,<br>    &quot;dsthostsrvrerrorrate&quot;: 0<br>}</pre><p>This test case gives the following result in <strong>POSTMAN:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*3_O9C9UvsZiD_5oWRSKwlQ.png" /></figure><p>Thus, the attack type is successfully identified as <strong>DoS.</strong></p><h3>8. Conclusion</h3><p>This project demonstrates a complete, production-oriented approach to network anomaly detection using classical machine learning. By combining EDA, Hypothesis Testing, preprocessing, and modeling, the system achieves high reliability.</p><p><strong>Future Scope:</strong></p><ul><li>Use of advanced Machine Learning/Deep Learning e.g. Neural Networks, to determine exact attack</li><li>Adding drift detection mechanisms to identify changes in network traffic patterns and trigger scheduled model retraining</li><li>Applying the model to live network traffic could increase real-world usefulness.</li></ul><p><em>Project Github: </em><a href="https://github.com/ad250997/Network-Anomaly-Detection"><em>Click here</em></a></p><p><em>Tableau Dashboard: </em><a href="https://public.tableau.com/views/NetworkAnomalyDetection_17668554667360/Dashboard1?:language=en-US&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link"><em>Click here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1adbbde1830f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>