Creating a machine learning model for intrusion detection is a complex task, especially when combining Transformers with automated machine learning (AutoML). I will help you write a Python outline to achieve this using the CICIDS2018 dataset, Transformers, and an AutoML library like TPOT. This outline will evaluate the specified metrics: accuracy, precision, recall, F1 score, false positive rate (FPR), and false negative rate (FNR).
python Copy code
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import roc_curve
from tpot import TPOTClassifier
import torch
import torch.nn as nn
from transformers import BertModel
# --- Step 1: Load & Preprocess Dataset ---
def load_and_preprocess_data(file_path):
# Load the dataset
df = pd.read_csv(file_path)
# Handle missing values (if required)
df = df.fillna(0)
# Encode categorical labels to numbers
if 'Label' in df.columns:
le = LabelEncoder()
df['Label'] = le.fit_transform(df['Label'])
# Separate features (X) and labels (y)
X = df.drop('Label', axis=1)
y = df['Label']
# Normalize or scale the features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Split dataset into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test
# --- Step 2: AutoML Using TPOT ---
def run_automl(X_train, X_test, y_train, y_test):
print("Running AutoML using TPOT...")
tpot = TPOTClassifier(generations=5, population_size=20, verbosity=2, random_state=42, scoring='f1')
tpot.fit(X_train, y_train)
y_pred = tpot.predict(X_test)
print(f"Chosen Pipeline: {tpot.fitted_pipeline_}")
return tpot, y_pred
# --- Step 3: Transformer Model ---
class IntrusionDetectionModel(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.sigmoid(self.fc3(x))
return x
def run_transformer_model(X_train, X_test, y_train, y_test):
print("Running Transformer Model...")
# Convert data to PyTorch tensors
X_train_t = torch.tensor(X_train, dtype=torch.float32)
y_train_t = torch.tensor(y_train.values, dtype=torch.float32).unsqueeze(1)
X_test_t = torch.tensor(X_test, dtype=torch.float32)
y_test_t = torch.tensor(y_test.values, dtype=torch.float32).unsqueeze(1)
# Define Transformer Model
input_dim = X_train.shape[1]
model = IntrusionDetectionModel(input_dim)
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Train the model
epochs = 10
for epoch in range(epochs):
model.train()
optimizer.zero_grad()
outputs = model(X_train_t)
loss = criterion(outputs, y_train_t)
loss.backward()
optimizer.step()
print(f"Epoch {epoch + 1}/{epochs}, Loss: {loss.item()}")
# Evaluate the model
model.eval()
with torch.no_grad():
y_pred = model(X_test_t)
y_pred_class = (y_pred > 0.5).int() # Threshold 0.5
return y_pred_class
# --- Step 4: Evaluate Metrics ---
def evaluate_metrics(y_test, y_pred):
print("Evaluating Metrics...")
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# False Positive Rate (FPR) and False Negative Rate (FNR)
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
fpr = fp / (fp + tn)
fnr = fn / (tp + fn)
print(f"Accuracy: {accuracy}")
print(f"Precision: {precision}")
print(f"Recall: {recall}")
print(f"F1 Score: {f1}")
print(f"False Positive Rate: {fpr}")
print(f"False Negative Rate: {fnr}")
return accuracy, precision, recall, f1, fpr, fnr
# --- Main Function ---
if __name__ == "__main__":
# Step 1: Load and preprocess data
dataset_path = "path_to_cicids2018.csv" # Replace this path with your dataset's path
X_train, X_test, y_train, y_test = load_and_preprocess_data(dataset_path)
# Step 2: Run AutoML (TPOT)
tpot, y_pred_automl = run_automl(X_train, X_test, y_train, y_test)
print("\n--- AutoML Results ---")
evaluate_metrics(y_test, y_pred_automl)
# Step 3: Run Transformer Model
y_pred_transformer = run_transformer_model(X_train, X_test, y_train, y_test)
print("\n--- Transformer Model Results ---")
evaluate_metrics(y_test, y_pred_transformer.numpy())