Certainly! Below are five different deep learning algorithms and techniques for phishing detection, implemented in Python using Keras (TensorFlow backend). Each implementation follows a similar structure to your current MLP setup, including data preprocessing, handling class imbalance with SMOTE, training, hyperparameter tuning, and evaluation.
The five models are:
- Deep Neural Network (DNN) using Keras Sequential API
- Convolutional Neural Network (CNN)
- Long Short-Term Memory (LSTM) Network
- Deep Neural Network with Dropout and Batch Normalization
- Ensemble of Multiple Neural Networks
Common Setup for All Models
We'll start by setting up the common data preprocessing steps shared across all models.
# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, classification_report,
confusion_matrix)
from sklearn.utils.class_weight import compute_class_weight
from imblearn.over_sampling import SMOTE
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Conv1D, MaxPooling1D, Flatten, LSTM, Input
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
# Read data
df = pd.read_csv('dataset_phishing.csv')
# Define features and target
features = ['shortest_word_path',
'ratio_intMedia',
'links_in_tags',
'nb_hyphens',
'page_rank',
'avg_word_path',
'ratio_extHyperlinks',
'longest_words_raw',
'google_index',
'length_hostname',
'longest_word_host',
'domain_registration_length',
'nb_www',
'nb_underscore',
'nb_dots',
'ratio_extMedia',
'phish_hints',
'domain_in_title',
'web_traffic',
'safe_anchor',
'nb_space',
'shortening_service',
'ip',
'domain_age',
'nb_qm',
'nb_hyperlinks',
'nb_slash']
X = df[features]
y = df["status"]
# Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Encode labels
le = LabelEncoder()
y_encoded = le.fit_transform(y)
# Splitting the data
X_train, X_temp, y_train, y_temp = train_test_split(
X_scaled, y_encoded, test_size=0.3, random_state=42, stratify=y_encoded)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, random_state=42)
# Handle class imbalance with SMOTE
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
1. Deep Neural Network (DNN) using Keras Sequential API
This model is similar to your existing MLP but implemented using Keras for more flexibility.
def create_dnn_model(input_dim=26, neurons=100, activation='relu', optimizer='adam'):
model = Sequential()
model.add(Dense(neurons, input_dim=input_dim, activation=activation))
model.add(Dense(neurons, activation=activation))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# Wrap the model using KerasClassifier
dnn = KerasClassifier(build_fn=create_dnn_model,
input_dim=X_resampled.shape[1],
neurons=100,
activation='relu',
optimizer='adam',
epochs=100,
batch_size=32,
verbose=0)
# Define hyperparameter grid
param_grid_dnn = {
'neurons': [100, 150],
'activation': ['relu', 'tanh'],
'optimizer': ['adam', 'rmsprop'],
'epochs': [100],
'batch_size': [32, 64]
}
# Grid Search
grid_dnn = GridSearchCV(estimator=dnn, param_grid=param_grid_dnn,
cv=5, scoring='recall', n_jobs=-1, verbose=2)
grid_dnn.fit(X_resampled, y_resampled)
# Best Model
best_dnn = grid_dnn.best_estimator_.model
# Evaluation on Validation Set
y_val_pred_dnn = (best_dnn.predict(X_val) > 0.5).astype("int32")
print("DNN Validation Metrics:")
print(classification_report(y_val, y_val_pred_dnn))
# Evaluation on Test Set
y_pred_dnn = (best_dnn.predict(X_test) > 0.5).astype("int32")
print("DNN Test Metrics:")
print(classification_report(y_test, y_pred_dnn))
# Confusion Matrix for Test Set
conf_matrix_dnn = confusion_matrix(y_test, y_pred_dnn)
sns.heatmap(conf_matrix_dnn, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (DNN Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
2. Convolutional Neural Network (CNN)
Although CNNs are typically used for image data, they can be adapted for structured data by treating feature vectors as 1D "images."
def create_cnn_model(input_dim=26, filters=64, kernel_size=2, activation='relu', optimizer='adam'):
model = Sequential()
model.add(Conv1D(filters=filters, kernel_size=kernel_size, activation=activation, input_shape=(input_dim, 1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(100, activation=activation))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# Reshape data for CNN
X_resampled_cnn = X_resampled.reshape((X_resampled.shape[0], X_resampled.shape[1], 1))
X_val_cnn = X_val.reshape((X_val.shape[0], X_val.shape[1], 1))
X_test_cnn = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
# Wrap the model using KerasClassifier
cnn = KerasClassifier(build_fn=create_cnn_model,
input_dim=X_resampled.shape[1],
filters=64,
kernel_size=2,
activation='relu',
optimizer='adam',
epochs=100,
batch_size=32,
verbose=0)
# Define hyperparameter grid
param_grid_cnn = {
'filters': [64, 128],
'kernel_size': [2, 3],
'activation': ['relu', 'tanh'],
'optimizer': ['adam', 'rmsprop'],
'epochs': [100],
'batch_size': [32, 64]
}
# Grid Search
grid_cnn = GridSearchCV(estimator=cnn, param_grid=param_grid_cnn,
cv=5, scoring='recall', n_jobs=-1, verbose=2)
grid_cnn.fit(X_resampled_cnn, y_resampled)
# Best Model
best_cnn = grid_cnn.best_estimator_.model
# Evaluation on Validation Set
y_val_pred_cnn = (best_cnn.predict(X_val_cnn) > 0.5).astype("int32")
print("CNN Validation Metrics:")
print(classification_report(y_val, y_val_pred_cnn))
# Evaluation on Test Set
y_pred_cnn = (best_cnn.predict(X_test_cnn) > 0.5).astype("int32")
print("CNN Test Metrics:")
print(classification_report(y_test, y_pred_cnn))
# Confusion Matrix for Test Set
conf_matrix_cnn = confusion_matrix(y_test, y_pred_cnn)
sns.heatmap(conf_matrix_cnn, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (CNN Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
3. Long Short-Term Memory (LSTM) Network
LSTMs are typically used for sequential data. Here, we'll treat feature vectors as sequences.
def create_lstm_model(input_dim=26, units=100, activation='tanh', optimizer='adam'):
model = Sequential()
model.add(LSTM(units=units, activation=activation, input_shape=(input_dim, 1)))
model.add(Dense(100, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# Wrap the model using KerasClassifier
lstm = KerasClassifier(build_fn=create_lstm_model,
input_dim=X_resampled.shape[1],
units=100,
activation='tanh',
optimizer='adam',
epochs=100,
batch_size=32,
verbose=0)
# Define hyperparameter grid
param_grid_lstm = {
'units': [100, 150],
'activation': ['tanh', 'relu'],
'optimizer': ['adam', 'rmsprop'],
'epochs': [100],
'batch_size': [32, 64]
}
# Grid Search
grid_lstm = GridSearchCV(estimator=lstm, param_grid=param_grid_lstm,
cv=5, scoring='recall', n_jobs=-1, verbose=2)
grid_lstm.fit(X_resampled_cnn, y_resampled)
# Best Model
best_lstm = grid_lstm.best_estimator_.model
# Evaluation on Validation Set
y_val_pred_lstm = (best_lstm.predict(X_val_cnn) > 0.5).astype("int32")
print("LSTM Validation Metrics:")
print(classification_report(y_val, y_val_pred_lstm))
# Evaluation on Test Set
y_pred_lstm = (best_lstm.predict(X_test_cnn) > 0.5).astype("int32")
print("LSTM Test Metrics:")
print(classification_report(y_test, y_pred_lstm))
# Confusion Matrix for Test Set
conf_matrix_lstm = confusion_matrix(y_test, y_pred_lstm)
sns.heatmap(conf_matrix_lstm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (LSTM Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
4. Deep Neural Network with Dropout and Batch Normalization
This model incorporates Dropout and Batch Normalization to prevent overfitting and stabilize training.
def create_dnn_dropout_bn(input_dim=26, neurons=128, activation='relu', optimizer='adam', dropout_rate=0.5):
model = Sequential()
model.add(Dense(neurons, input_dim=input_dim, activation=activation))
model.add(BatchNormalization())
model.add(Dropout(dropout_rate))
model.add(Dense(neurons, activation=activation))
model.add(BatchNormalization())
model.add(Dropout(dropout_rate))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# Wrap the model using KerasClassifier
dnn_dropout_bn = KerasClassifier(build_fn=create_dnn_dropout_bn,
input_dim=X_resampled.shape[1],
neurons=128,
activation='relu',
optimizer='adam',
dropout_rate=0.5,
epochs=100,
batch_size=32,
verbose=0)
# Define hyperparameter grid
param_grid_dnn_dropout_bn = {
'neurons': [128, 256],
'activation': ['relu', 'tanh'],
'optimizer': ['adam', 'nadam'],
'dropout_rate': [0.3, 0.5],
'epochs': [100],
'batch_size': [32, 64]
}
# Grid Search
grid_dnn_dropout_bn = GridSearchCV(estimator=dnn_dropout_bn,
param_grid=param_grid_dnn_dropout_bn,
cv=5, scoring='recall', n_jobs=-1, verbose=2)
grid_dnn_dropout_bn.fit(X_resampled, y_resampled)
# Best Model
best_dnn_dropout_bn = grid_dnn_dropout_bn.best_estimator_.model
# Evaluation on Validation Set
y_val_pred_dnn_dropout_bn = (best_dnn_dropout_bn.predict(X_val) > 0.5).astype("int32")
print("DNN with Dropout & BN Validation Metrics:")
print(classification_report(y_val, y_val_pred_dnn_dropout_bn))
# Evaluation on Test Set
y_pred_dnn_dropout_bn = (best_dnn_dropout_bn.predict(X_test) > 0.5).astype("int32")
print("DNN with Dropout & BN Test Metrics:")
print(classification_report(y_test, y_pred_dnn_dropout_bn))
# Confusion Matrix for Test Set
conf_matrix_dnn_dropout_bn = confusion_matrix(y_test, y_pred_dnn_dropout_bn)
sns.heatmap(conf_matrix_dnn_dropout_bn, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (DNN with Dropout & BN Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
5. Ensemble of Multiple Neural Networks
Ensemble methods can improve performance by combining predictions from multiple models.
from tensorflow.keras.models import clone_model
from sklearn.metrics import confusion_matrix
# Define number of models in the ensemble
n_ensemble = 3
ensemble_models = []
# Create and train ensemble models
for i in range(n_ensemble):
print(f"Training ensemble model {i+1}/{n_ensemble}")
model = create_dnn_model(input_dim=X_resampled.shape[1], neurons=100, activation='relu', optimizer='adam')
history = model.fit(X_resampled, y_resampled,
epochs=100,
batch_size=32,
verbose=0,
validation_data=(X_val, y_val),
callbacks=[EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)])
ensemble_models.append(model)
# Function to make ensemble predictions
def ensemble_predict(models, X):
preds = [model.predict(X) for model in models]
preds = np.array(preds)
preds_mean = preds.mean(axis=0)
return (preds_mean > 0.5).astype("int32")
# Evaluation on Validation Set
y_val_pred_ensemble = ensemble_predict(ensemble_models, X_val)
print("Ensemble Validation Metrics:")
print(classification_report(y_val, y_val_pred_ensemble))
# Evaluation on Test Set
y_pred_ensemble = ensemble_predict(ensemble_models, X_test)
print("Ensemble Test Metrics:")
print(classification_report(y_test, y_pred_ensemble))
# Confusion Matrix for Test Set
conf_matrix_ensemble = confusion_matrix(y_test, y_pred_ensemble)
sns.heatmap(conf_matrix_ensemble, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (Ensemble Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
Summary and Tips
-
Hyperparameter Tuning: Each model uses GridSearchCV for hyperparameter tuning. Depending on computational resources, you might want to adjust the hyperparameter grid to balance performance and training time.
-
Early Stopping: For the ensemble model, EarlyStopping is used to prevent overfitting by monitoring the validation loss.
-
Reshaping Data for CNN and LSTM: CNN and LSTM models require the input data to have specific shapes. Ensure that data is reshaped appropriately as shown.
-
Class Imbalance: SMOTE is used to handle class imbalance in the training set. Ensure that oversampling is only applied to the training data to prevent data leakage.
-
Evaluation Metrics: The primary metric used is recall during hyperparameter tuning since phishing detection often prioritizes minimizing false negatives.
-
Visualization: Confusion matrices are plotted for each model on the test set to visualize performance.
-
Reproducibility: Set random seeds if you need reproducible results across different runs.
Final Thoughts
Implementing multiple deep learning models allows you to compare their performance and choose the best one for your phishing detection task. Ensemble methods, in particular, can leverage the strengths of individual models to achieve better overall performance. Always ensure to validate and test models properly to avoid overfitting and to generalize well on unseen data.