Cyber threats are a growing concern for organizations worldwide. These threats take many forms, including malware, phishing, and denial-of-service (DOS) attacks, compromising sensitive information and disrupting operations. The increasing sophistication and frequency of these attacks make it imperative for organizations to adopt advanced security measures. Traditional threat detection methods often fall short due to their inability to adapt to new and evolving threats. This is where deep learning models come into play.
Deep learning models can analyze vast amounts of data and identify patterns that may not be immediately obvious to human analysts. By leveraging these models, organizations can proactively detect and mitigate cyber threats, safeguarding their sensitive information and ensuring operational continuity.
As a cybersecurity analyst, you identify and mitigate these threats. In this project, you will design and implement a deep learning model to detect cyber threats. The BETH dataset simulates real-world logs, providing a rich source of information for training and testing your model. The data has already undergone preprocessing, and we have a target label, sus_label
, indicating whether an event is malicious (1) or benign (0).
By successfully developing this model, you will contribute to enhancing cybersecurity measures and protecting organizations from potentially devastating cyber attacks.
The Data
Column | Description |
---|---|
processId | The unique identifier for the process that generated the event - int64 |
threadId | ID for the thread spawning the log - int64 |
parentProcessId | Label for the process spawning this log - int64 |
userId | ID of user spawning the log |
mountNamespace | Mounting restrictions the process log works within - int64 |
argsNum | Number of arguments passed to the event - int64 |
returnValue | Value returned from the event log (usually 0) - int64 |
sus_label | Binary label as suspicous event (1 is suspicious, 0 is not) - int64 |
More information on the dataset: BETH dataset (Invalid URL)
# Make sure to run this cell to use torchmetrics. If you cannot use pip install to install the torchmetrics, you can use sklearn.
!pip install torchmetrics
# Import required libraries
import pandas as pd
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.nn.functional as f
from torch.utils.data import DataLoader, TensorDataset
import torch.optim as optim
from torchmetrics import Accuracy
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# Load preprocessed data
train_df = pd.read_csv('labelled_train.csv')
test_df = pd.read_csv('labelled_test.csv')
val_df = pd.read_csv('labelled_validation.csv')
# View the first 5 rows of training set
train_df.head()
# Extract features and labels
X_train = train_df.drop('sus_label', axis=1)
y_train = train_df['sus_label']
X_val = val_df.drop('sus_label', axis=1)
y_val = val_df['sus_label']
X_test = test_df.drop('sus_label', axis=1)
y_test = test_df['sus_label']
# sus_label is our target
# Start coding here
# Use as many cells as you need
# Standardizing features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_val_scaled = scaler.transform(X_val)
X_test_scaled = scaler.transform(X_test)
## convert them into pytorch tensors
X_train_tensor = torch.tensor(X_train_scaled, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32)
X_val_tensor = torch.tensor(X_val_scaled, dtype=torch.float32)
y_val_tensor = torch.tensor(y_val.values, dtype=torch.float32)
X_test_tensor = torch.tensor(X_test_scaled, dtype=torch.float32)
y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32)
# Next create DataLoader for training
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
## our custiom nn model
class CyberAttackModel(nn.Module):
def __init__(self):
super(CyberAttackModel, self).__init__()
self.fc1 = nn.Linear(in_features=X_train_scaled.shape[1], out_features=64)
self.fc2 = nn.Linear(in_features=64, out_features=32)
self.fc3 = nn.Linear(in_features=32, out_features=1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
x = torch.sigmoid(x) # Sigmoid activation for binary classification
return x
# Initialize the loss function and optimizer
model = CyberAttackModel()
criterion = nn.BCELoss() # Binary Cross-Entropy Loss
optimizer = optim.SGD(model.parameters(),lr=1e-3, weight_decay=1e-4)
# Training
epochs = 20
for epoch in range(epochs):
model.train()
running_loss = 0.0
for batch_X, batch_y in train_loader:
# Forward pass
outputs = model(batch_X).squeeze()
loss = criterion(outputs, batch_y)
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item() * batch_X.size(0)
epoch_loss = running_loss / len(train_loader.dataset)
print(f'Epoch [{epoch + 1}/{epochs}], Loss: {epoch_loss:.4f}')
model.eval()
with torch.no_grad():
# Predict on validation set
val_outputs = model(X_val_tensor).squeeze()
val_predictions = (val_outputs > 0.5).float() # Apply threshold
# Calculate accuracy
val_accuracy = accuracy_score(y_val_tensor, val_predictions)
val_accuracy_int = int(val_accuracy * 100) # Convert to integer percentage
print(f'Validation Accuracy: {val_accuracy_int}%')
model.eval()
with torch.no_grad():
# Predict on test set
test_outputs = model(X_test_tensor).squeeze()
test_predictions = (test_outputs > 0.5).float() # Apply threshold
# Calculate test accuracy
test_accuracy = accuracy_score(y_test_tensor, test_predictions)
test_accuracy_int = int(test_accuracy * 100) # Convert to integer percentage
print(f'Test Accuracy: {test_accuracy_int}%')