Introduction

In this project, we explore network intrusion detection using machine learning techniques. We aim to classify network traffic as either normal or malicious based on various features in the dataset.

Data Preprocessing

Loading the Data

# Load the required libraries
library(ROCR)
## Warning: package 'ROCR' was built under R version 4.3.2
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(caret)
## Warning: package 'caret' was built under R version 4.3.2
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(ModelMetrics)
## Warning: package 'ModelMetrics' was built under R version 4.3.2
## 
## Attaching package: 'ModelMetrics'
## 
## The following objects are masked from 'package:caret':
## 
##     confusionMatrix, precision, recall, sensitivity, specificity
## 
## The following object is masked from 'package:base':
## 
##     kappa
library(pROC)
## Warning: package 'pROC' was built under R version 4.3.2
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## 
## The following object is masked from 'package:ModelMetrics':
## 
##     auc
## 
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
train <- read.csv("UNSW_NB15_training-set.csv")
test <- read.csv("UNSW_NB15_testing-set.csv")

summary(train)
##        id              dur              proto             service         
##  Min.   :     1   Min.   : 0.00000   Length:175341      Length:175341     
##  1st Qu.: 43836   1st Qu.: 0.00001   Class :character   Class :character  
##  Median : 87671   Median : 0.00158   Mode  :character   Mode  :character  
##  Mean   : 87671   Mean   : 1.35939                                        
##  3rd Qu.:131506   3rd Qu.: 0.66807                                        
##  Max.   :175341   Max.   :59.99999                                        
##     state               spkts            dpkts              sbytes        
##  Length:175341      Min.   :   1.0   Min.   :    0.00   Min.   :      28  
##  Class :character   1st Qu.:   2.0   1st Qu.:    0.00   1st Qu.:     114  
##  Mode  :character   Median :   2.0   Median :    2.00   Median :     430  
##                     Mean   :  20.3   Mean   :   18.97   Mean   :    8845  
##                     3rd Qu.:  12.0   3rd Qu.:   10.00   3rd Qu.:    1418  
##                     Max.   :9616.0   Max.   :10974.00   Max.   :12965233  
##      dbytes              rate                sttl            dttl       
##  Min.   :       0   Min.   :      0.0   Min.   :  0.0   Min.   :  0.00  
##  1st Qu.:       0   1st Qu.:     32.8   1st Qu.: 62.0   1st Qu.:  0.00  
##  Median :     164   Median :   3225.8   Median :254.0   Median : 29.00  
##  Mean   :   14929   Mean   :  95406.2   Mean   :179.5   Mean   : 79.61  
##  3rd Qu.:    1102   3rd Qu.: 125000.0   3rd Qu.:254.0   3rd Qu.:252.00  
##  Max.   :14655550   Max.   :1000000.0   Max.   :255.0   Max.   :254.00  
##      sload               dload              sloss              dloss         
##  Min.   :0.000e+00   Min.   :       0   Min.   :   0.000   Min.   :   0.000  
##  1st Qu.:1.305e+04   1st Qu.:       0   1st Qu.:   0.000   1st Qu.:   0.000  
##  Median :8.797e+05   Median :    1447   Median :   0.000   Median :   0.000  
##  Mean   :7.345e+07   Mean   :  671206   Mean   :   4.953   Mean   :   6.948  
##  3rd Qu.:8.889e+07   3rd Qu.:   27845   3rd Qu.:   3.000   3rd Qu.:   2.000  
##  Max.   :5.988e+09   Max.   :22422730   Max.   :4803.000   Max.   :5484.000  
##      sinpkt             dinpkt              sjit              djit         
##  Min.   :    0.00   Min.   :    0.00   Min.   :      0   Min.   :     0.0  
##  1st Qu.:    0.01   1st Qu.:    0.00   1st Qu.:      0   1st Qu.:     0.0  
##  Median :    0.28   Median :    0.01   Median :      0   Median :     0.0  
##  Mean   :  985.98   Mean   :   88.22   Mean   :   4976   Mean   :   604.4  
##  3rd Qu.:   55.16   3rd Qu.:   51.05   3rd Qu.:   2513   3rd Qu.:   115.0  
##  Max.   :84371.50   Max.   :56716.82   Max.   :1460480   Max.   :289388.3  
##       swin           stcpb               dtcpb                dwin    
##  Min.   :  0.0   Min.   :0.000e+00   Min.   :0.000e+00   Min.   :  0  
##  1st Qu.:  0.0   1st Qu.:0.000e+00   1st Qu.:0.000e+00   1st Qu.:  0  
##  Median :  0.0   Median :0.000e+00   Median :0.000e+00   Median :  0  
##  Mean   :116.3   Mean   :9.693e+08   Mean   :9.689e+08   Mean   :115  
##  3rd Qu.:255.0   3rd Qu.:1.917e+09   3rd Qu.:1.914e+09   3rd Qu.:255  
##  Max.   :255.0   Max.   :4.295e+09   Max.   :4.295e+09   Max.   :255  
##      tcprtt            synack            ackdat            smean       
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :  28.0  
##  1st Qu.:0.00000   1st Qu.:0.00000   1st Qu.:0.00000   1st Qu.:  57.0  
##  Median :0.00000   Median :0.00000   Median :0.00000   Median :  73.0  
##  Mean   :0.04140   Mean   :0.02102   Mean   :0.02038   Mean   : 136.8  
##  3rd Qu.:0.06548   3rd Qu.:0.02327   3rd Qu.:0.03891   3rd Qu.: 100.0  
##  Max.   :2.51889   Max.   :2.10035   Max.   :1.52088   Max.   :1504.0  
##      dmean         trans_depth      response_body_len   ct_srv_src    
##  Min.   :   0.0   Min.   :  0.000   Min.   :      0   Min.   : 1.000  
##  1st Qu.:   0.0   1st Qu.:  0.000   1st Qu.:      0   1st Qu.: 2.000  
##  Median :  44.0   Median :  0.000   Median :      0   Median : 5.000  
##  Mean   : 124.2   Mean   :  0.106   Mean   :   2144   Mean   : 9.306  
##  3rd Qu.:  89.0   3rd Qu.:  0.000   3rd Qu.:      0   3rd Qu.:12.000  
##  Max.   :1458.0   Max.   :172.000   Max.   :6558056   Max.   :63.000  
##   ct_state_ttl     ct_dst_ltm     ct_src_dport_ltm ct_dst_sport_ltm
##  Min.   :0.000   Min.   : 1.000   Min.   : 1.000   Min.   : 1.000  
##  1st Qu.:1.000   1st Qu.: 1.000   1st Qu.: 1.000   1st Qu.: 1.000  
##  Median :1.000   Median : 2.000   Median : 1.000   Median : 1.000  
##  Mean   :1.304   Mean   : 6.194   Mean   : 5.384   Mean   : 4.206  
##  3rd Qu.:2.000   3rd Qu.: 7.000   3rd Qu.: 5.000   3rd Qu.: 3.000  
##  Max.   :6.000   Max.   :51.000   Max.   :51.000   Max.   :46.000  
##  ct_dst_src_ltm   is_ftp_login       ct_ftp_cmd      ct_flw_http_mthd 
##  Min.   : 1.00   Min.   :0.00000   Min.   :0.00000   Min.   : 0.0000  
##  1st Qu.: 1.00   1st Qu.:0.00000   1st Qu.:0.00000   1st Qu.: 0.0000  
##  Median : 3.00   Median :0.00000   Median :0.00000   Median : 0.0000  
##  Mean   : 8.73   Mean   :0.01495   Mean   :0.01495   Mean   : 0.1331  
##  3rd Qu.:12.00   3rd Qu.:0.00000   3rd Qu.:0.00000   3rd Qu.: 0.0000  
##  Max.   :65.00   Max.   :4.00000   Max.   :4.00000   Max.   :30.0000  
##    ct_src_ltm       ct_srv_dst     is_sm_ips_ports    attack_cat       
##  Min.   : 1.000   Min.   : 1.000   Min.   :0.00000   Length:175341     
##  1st Qu.: 2.000   1st Qu.: 2.000   1st Qu.:0.00000   Class :character  
##  Median : 3.000   Median : 4.000   Median :0.00000   Mode  :character  
##  Mean   : 6.956   Mean   : 9.101   Mean   :0.01575                     
##  3rd Qu.: 9.000   3rd Qu.:12.000   3rd Qu.:0.00000                     
##  Max.   :60.000   Max.   :62.000   Max.   :1.00000                     
##      label       
##  Min.   :0.0000  
##  1st Qu.:0.0000  
##  Median :1.0000  
##  Mean   :0.6806  
##  3rd Qu.:1.0000  
##  Max.   :1.0000
summary(test)
##        id             dur              proto             service         
##  Min.   :    1   Min.   : 0.00000   Length:82332       Length:82332      
##  1st Qu.:20584   1st Qu.: 0.00001   Class :character   Class :character  
##  Median :41167   Median : 0.01414   Mode  :character   Mode  :character  
##  Mean   :41167   Mean   : 1.00676                                        
##  3rd Qu.:61749   3rd Qu.: 0.71936                                        
##  Max.   :82332   Max.   :59.99999                                        
##     state               spkts              dpkts              sbytes        
##  Length:82332       Min.   :    1.00   Min.   :    0.00   Min.   :      24  
##  Class :character   1st Qu.:    2.00   1st Qu.:    0.00   1st Qu.:     114  
##  Mode  :character   Median :    6.00   Median :    2.00   Median :     534  
##                     Mean   :   18.67   Mean   :   17.55   Mean   :    7994  
##                     3rd Qu.:   12.00   3rd Qu.:   10.00   3rd Qu.:    1280  
##                     Max.   :10646.00   Max.   :11018.00   Max.   :14355774  
##      dbytes              rate                sttl          dttl       
##  Min.   :       0   Min.   :      0.0   Min.   :  0   Min.   :  0.00  
##  1st Qu.:       0   1st Qu.:     28.6   1st Qu.: 62   1st Qu.:  0.00  
##  Median :     178   Median :   2650.2   Median :254   Median : 29.00  
##  Mean   :   13234   Mean   :  82410.9   Mean   :181   Mean   : 95.71  
##  3rd Qu.:     956   3rd Qu.: 111111.1   3rd Qu.:254   3rd Qu.:252.00  
##  Max.   :14657531   Max.   :1000000.0   Max.   :255   Max.   :253.00  
##      sload               dload              sloss              dloss         
##  Min.   :0.000e+00   Min.   :       0   Min.   :   0.000   Min.   :   0.000  
##  1st Qu.:1.120e+04   1st Qu.:       0   1st Qu.:   0.000   1st Qu.:   0.000  
##  Median :5.770e+05   Median :    2113   Median :   1.000   Median :   0.000  
##  Mean   :6.455e+07   Mean   :  630547   Mean   :   4.754   Mean   :   6.309  
##  3rd Qu.:6.514e+07   3rd Qu.:   15858   3rd Qu.:   3.000   3rd Qu.:   2.000  
##  Max.   :5.268e+09   Max.   :20821108   Max.   :5319.000   Max.   :5507.000  
##      sinpkt             dinpkt              sjit                djit         
##  Min.   :    0.00   Min.   :    0.00   Min.   :      0.0   Min.   :     0.0  
##  1st Qu.:    0.01   1st Qu.:    0.00   1st Qu.:      0.0   1st Qu.:     0.0  
##  Median :    0.56   Median :    0.01   Median :     17.6   Median :     0.0  
##  Mean   :  755.39   Mean   :  121.70   Mean   :   6363.1   Mean   :   535.2  
##  3rd Qu.:   63.41   3rd Qu.:   63.14   3rd Qu.:   3219.3   3rd Qu.:   128.5  
##  Max.   :60009.99   Max.   :57739.24   Max.   :1483830.9   Max.   :463199.2  
##       swin           stcpb               dtcpb                dwin      
##  Min.   :  0.0   Min.   :0.000e+00   Min.   :0.000e+00   Min.   :  0.0  
##  1st Qu.:  0.0   1st Qu.:0.000e+00   1st Qu.:0.000e+00   1st Qu.:  0.0  
##  Median :255.0   Median :2.789e+07   Median :2.857e+07   Median :255.0  
##  Mean   :133.5   Mean   :1.085e+09   Mean   :1.073e+09   Mean   :128.3  
##  3rd Qu.:255.0   3rd Qu.:2.171e+09   3rd Qu.:2.144e+09   3rd Qu.:255.0  
##  Max.   :255.0   Max.   :4.295e+09   Max.   :4.295e+09   Max.   :255.0  
##      tcprtt             synack             ackdat            smean       
##  Min.   :0.000000   Min.   :0.000000   Min.   :0.00000   Min.   :  24.0  
##  1st Qu.:0.000000   1st Qu.:0.000000   1st Qu.:0.00000   1st Qu.:  57.0  
##  Median :0.000551   Median :0.000441   Median :0.00008   Median :  65.0  
##  Mean   :0.055925   Mean   :0.029256   Mean   :0.02667   Mean   : 139.5  
##  3rd Qu.:0.105541   3rd Qu.:0.052596   3rd Qu.:0.04882   3rd Qu.: 100.0  
##  Max.   :3.821465   Max.   :3.226788   Max.   :2.92878   Max.   :1504.0  
##      dmean         trans_depth        response_body_len   ct_srv_src    
##  Min.   :   0.0   Min.   :  0.00000   Min.   :      0   Min.   : 1.000  
##  1st Qu.:   0.0   1st Qu.:  0.00000   1st Qu.:      0   1st Qu.: 2.000  
##  Median :  44.0   Median :  0.00000   Median :      0   Median : 5.000  
##  Mean   : 116.3   Mean   :  0.09428   Mean   :   1595   Mean   : 9.547  
##  3rd Qu.:  87.0   3rd Qu.:  0.00000   3rd Qu.:      0   3rd Qu.:11.000  
##  Max.   :1500.0   Max.   :131.00000   Max.   :5242880   Max.   :63.000  
##   ct_state_ttl     ct_dst_ltm     ct_src_dport_ltm ct_dst_sport_ltm
##  Min.   :0.000   Min.   : 1.000   Min.   : 1.000   Min.   : 1.000  
##  1st Qu.:1.000   1st Qu.: 1.000   1st Qu.: 1.000   1st Qu.: 1.000  
##  Median :1.000   Median : 2.000   Median : 1.000   Median : 1.000  
##  Mean   :1.369   Mean   : 5.745   Mean   : 4.929   Mean   : 3.663  
##  3rd Qu.:2.000   3rd Qu.: 6.000   3rd Qu.: 4.000   3rd Qu.: 3.000  
##  Max.   :6.000   Max.   :59.000   Max.   :59.000   Max.   :38.000  
##  ct_dst_src_ltm    is_ftp_login        ct_ftp_cmd       ct_flw_http_mthd 
##  Min.   : 1.000   Min.   :0.000000   Min.   :0.000000   Min.   : 0.0000  
##  1st Qu.: 1.000   1st Qu.:0.000000   1st Qu.:0.000000   1st Qu.: 0.0000  
##  Median : 3.000   Median :0.000000   Median :0.000000   Median : 0.0000  
##  Mean   : 7.456   Mean   :0.008283   Mean   :0.008381   Mean   : 0.1297  
##  3rd Qu.: 6.000   3rd Qu.:0.000000   3rd Qu.:0.000000   3rd Qu.: 0.0000  
##  Max.   :63.000   Max.   :2.000000   Max.   :2.000000   Max.   :16.0000  
##    ct_src_ltm       ct_srv_dst     is_sm_ips_ports    attack_cat       
##  Min.   : 1.000   Min.   : 1.000   Min.   :0.00000   Length:82332      
##  1st Qu.: 1.000   1st Qu.: 2.000   1st Qu.:0.00000   Class :character  
##  Median : 3.000   Median : 5.000   Median :0.00000   Mode  :character  
##  Mean   : 6.468   Mean   : 9.164   Mean   :0.01113                     
##  3rd Qu.: 7.000   3rd Qu.:11.000   3rd Qu.:0.00000                     
##  Max.   :60.000   Max.   :62.000   Max.   :1.00000                     
##      label       
##  Min.   :0.0000  
##  1st Qu.:0.0000  
##  Median :1.0000  
##  Mean   :0.5506  
##  3rd Qu.:1.0000  
##  Max.   :1.0000
#Model 1

# Convert categorical variables to factors
# Note: Adjust these variable names if they are different in your dataset
train$proto <- as.factor(train$proto)   # Protocol type
train$state <- as.factor(train$state)   # State of the connection
train$service <- as.factor(train$service) # Network service type

eval_data = read.csv("UNSW_NB15_testing-set.csv")
# You can also convert other categorical variables as needed


# Assuming the 'train' dataset is already loaded and prepared

# Build the logistic regression model
# The 'label' variable is used as the dependent variable (the one to predict)
# 'dur', 'proto', 'sbytes', 'dbytes', 'spkts', 'dpkts', 'rate', 'state', and 'service' are the independent variables (predictors)
#glm.fit <- glm(label ~ dur + proto + sbytes + dbytes + spkts + dpkts + rate + state + service, 
          #     data = train, family = binomial)

# View the summary of the model
#summary(glm.fit)

# Convert categorical variables to factors
# Note: Adjust these variable names if they are different in your dataset
train$proto <- as.factor(train$proto)   # Protocol type
train$state <- as.factor(train$state)   # State of the connection
train$service <- as.factor(train$service) # Network service type


# Build the logistic regression model
# The 'label' variable is used as the dependent variable (the one to predict)
# 'dur', 'proto', 'sbytes', 'dbytes', 'spkts', 'dpkts', 'rate', 'state', and 'service' are the independent variables (predictors)
glm.fit.2 <- glm(label ~ dur + proto + sbytes + dbytes + spkts + dpkts + rate + state + service, 
              data = train, family = binomial)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
# View the summary of the model
#summary(glm.fit2)

test <- test[!test$state %in% c("ACC", "CLO"), ]


# Predict probabilities on the test dataset
predictions <- predict(glm.fit.2, newdata = test, type = "response")

# Convert probabilities to a binary classification based on a threshold (e.g., 0.5)
predicted_classes <- ifelse(predictions > 0.5, 1, 0)

# Create the confusion matrix
conf_matrix <- confusionMatrix(as.factor(predicted_classes), as.factor(test$label))

# Print the confusion matrix
print(conf_matrix)
##      [,1]  [,2]
## [1,]    0     0
## [2,]    0 21980
#Model 2

# Read the dataset
eval_data <- read.csv("UNSW_NB15_training-set.csv")


# Feature engineering
# Creating a new feature as an interaction term
train$interaction_feature <- train$sbytes * train$rate
test$interaction_feature <- test$sbytes * test$rate

# Building the logistic regression model with the new feature
glm.fit.improved <- glm(label ~ dur + proto + sbytes + dbytes + spkts + dpkts + 
                        rate + state + service + interaction_feature, 
                        data = train, family = binomial)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
# Remove rows with new levels from the test dataset
test <- test[!test$state %in% c("ACC", "CLO"), ]


# Predict probabilities on the test dataset
improved_predictions <- predict(glm.fit.improved, newdata = test, type = "response")

# Convert probabilities to a binary classification
predicted_classes_improved <- ifelse(improved_predictions > 0.5, 1, 0)

# Create the confusion matrix
conf_matrix_improved <- confusionMatrix(as.factor(predicted_classes_improved), as.factor(test$label))

# Print the confusion matrix
print(conf_matrix_improved)
##      [,1]  [,2]
## [1,]    0     0
## [2,]    0 21985
#Model 3


# Rebuild the model with only significant predictors

glm.fit.simplified <- glm(label ~ dur + sbytes + dbytes + spkts + dpkts + rate + (state == 'FIN') + (service == 'http'), 
                          data = train, family = binomial)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
# View the summary of the simplified model
#summary(glm.fit.simplified)

# Step 1: Make predictions on the evaluation dataset
predictions <- predict(glm.fit.simplified, eval_data, type = "response")

# Step 2: Create a prediction object
prediction_obj <- prediction(predictions, eval_data$label)

# Step 3: Calculate Precision-Recall curve
pr_obj <- performance(prediction_obj, "prec", "rec")

# Step 4: Calculate F1 Score
f1_score <- 2 * (pr_obj@x.values[[1]] * pr_obj@y.values[[1]]) / (pr_obj@x.values[[1]] + pr_obj@y.values[[1]])
cat("F1 Score:", max(f1_score), "\n")
## F1 Score: NaN
# Assuming 'eval_data' contains your evaluation dataset with labels
# Assuming 'predictions' contains your model's predictions

# Step 8: Calculate Confusion Matrix
conf_matrix <- table(eval_data$label, ifelse(predictions > 0.5, 1, 0))

# Print Confusion Matrix
cat("Confusion Matrix:\n")
## Confusion Matrix:
print(conf_matrix)
##    
##          0      1
##   0  37138  18862
##   1   8131 111210