Creating a high-performing Convolutional Neural Network (CNN) for phishing URL detection using tabular data involves several steps, including data preprocessing, model design, optimization techniques, and hyperparameter tuning. Below is a comprehensive guide to building the best possible CNN model for your dataset, incorporating state-of-the-art deep learning optimizations.
Note: While CNNs are traditionally used for image and sequence data, they can be adapted for tabular data. However, other models like Gradient Boosting Machines (e.g., XGBoost, LightGBM) or fully connected deep neural networks might sometimes perform better on tabular data. Nonetheless, we'll proceed with a CNN approach as per your request.
1. Data Preprocessing
a. Import Necessary Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
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)
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, Dense, Flatten, Dropout, BatchNormalization, MaxPooling1D
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import StratifiedKFold
from sklearn.utils import class_weight
import kerastuner as kt
b. Load and Preprocess Data
# Read data
data = pd.read_csv('dataset_phishing.csv')
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 = data[features]
y = data['status'] # Assuming 'status' is 1 for phishing and 0 for legitimate
# Handle missing values
X.fillna(0, inplace=True)
# Encode labels if not already numerical
if y.dtype == 'object':
le = LabelEncoder()
y = le.fit_transform(y)
# Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Reshape data for CNN: (samples, steps, features)
# Here, we'll treat each feature as a "step" with 1 feature per step
X_scaled = X_scaled.reshape((X_scaled.shape[0], X_scaled.shape[1], 1))
# Train-Test Split with stratification
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42, stratify=y
)
2. Building the CNN Model
a. Define the Model Architecture
We'll define a function to create the CNN model. This allows for easier hyperparameter tuning later.
def build_cnn_model(hp):
model = Sequential()
# First Conv1D layer
model.add(Conv1D(
filters=hp.Int('filters_1', min_value=32, max_value=128, step=32),
kernel_size=hp.Choice('kernel_size_1', values=[2,3,4]),
activation='relu',
input_shape=(X_train.shape[1], X_train.shape[2])
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
# Second Conv1D layer
model.add(Conv1D(
filters=hp.Int('filters_2', min_value=32, max_value=128, step=32),
kernel_size=hp.Choice('kernel_size_2', values=[2,3,4]),
activation='relu'
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
# Third Conv1D layer (optional)
if hp.Boolean('use_conv_3'):
model.add(Conv1D(
filters=hp.Int('filters_3', min_value=32, max_value=128, step=32),
kernel_size=hp.Choice('kernel_size_3', values=[2,3,4]),
activation='relu'
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
# Fully connected layers
for i in range(hp.Int('num_dense_layers', 1, 3)):
model.add(Dense(units=hp.Int(f'units_{i}', min_value=32, max_value=256, step=32), activation='relu'))
model.add(Dropout(rate=hp.Float(f'dropout_{i}', min_value=0.2, max_value=0.5, step=0.1)))
# Output layer
model.add(Dense(1, activation='sigmoid'))
# Compile model
model.compile(
optimizer=Adam(
learning_rate=hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, sampling='LOG')
),
loss='binary_crossentropy',
metrics=['accuracy', tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.AUC()]
)
return model
b. Hyperparameter Tuning with Keras Tuner
We'll use Keras Tuner to find the optimal hyperparameters.
# Initialize Keras Tuner
tuner = kt.Hyperband(
build_cnn_model,
objective='val_accuracy',
max_epochs=50,
factor=3,
directory='kt_dir',
project_name='phishing_cnn'
)
# Define callbacks
stop_early = EarlyStopping(monitor='val_loss', patience=10)
c. Execute the Hyperparameter Search
# Perform Hyperparameter Search
tuner.search(
X_train, y_train,
epochs=100,
validation_split=0.2,
callbacks=[stop_early],
batch_size=hp.Choice('batch_size', values=[32, 64, 128])
)
Note: The above code may throw an error because hp is not defined outside the build_cnn_model function. To set the batch size as a hyperparameter, it needs to be integrated within the tuner search. Alternatively, fix the batch size or handle it differently. However, Keras Tuner does not support hyperparameters outside the model-building function directly within search(). To keep it simple, we'll fix the batch size or exclude it from tuning.
Revised Approach:
Instead of tuning batch size with Keras Tuner, we'll define it outside.
# Set batch size (fixed or tuned separately)
batch_size = 64 # Choose a reasonable default
# Perform Hyperparameter Search
tuner.search(
X_train, y_train,
epochs=100,
validation_split=0.2,
callbacks=[stop_early],
batch_size=batch_size
)
d. Retrieve the Best Model
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete.
Optimal number of filters in first Conv1D layer: {best_hps.get('filters_1')}
Optimal kernel size in first Conv1D layer: {best_hps.get('kernel_size_1')}
Optimal number of filters in second Conv1D layer: {best_hps.get('filters_2')}
Optimal kernel size in second Conv1D layer: {best_hps.get('kernel_size_2')}
Learning rate for the optimizer: {best_hps.get('learning_rate')}
""")
# Build the best model
model = tuner.hypermodel.build(best_hps)
e. Train the Best Model with Callbacks and Class Weights
# Calculate class weights if classes are imbalanced
class_weights = class_weight.compute_class_weight(
class_weight='balanced',
classes=np.unique(y_train),
y=y_train
)
class_weights = dict(enumerate(class_weights))
# Define additional callbacks
callbacks = [
EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True),
ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, min_lr=1e-6)
]
# Train the model
history = model.fit(
X_train, y_train,
epochs=200,
validation_split=0.2,
callbacks=callbacks,
class_weight=class_weights,
batch_size=batch_size
)
3. Model Evaluation
a. Plot Training History
# Plot training & validation accuracy and loss
def plot_history(history):
fig, axs = plt.subplots(2, 2, figsize=(15,10))
# Accuracy
axs[0,0].plot(history.history['accuracy'], label='Train Accuracy')
axs[0,0].plot(history.history['val_accuracy'], label='Val Accuracy')
axs[0,0].set_title('Accuracy')
axs[0,0].legend()
# Loss
axs[0,1].plot(history.history['loss'], label='Train Loss')
axs[0,1].plot(history.history['val_loss'], label='Val Loss')
axs[0,1].set_title('Loss')
axs[0,1].legend()
# Precision
axs[1,0].plot(history.history['precision'], label='Train Precision')
axs[1,0].plot(history.history['val_precision'], label='Val Precision')
axs[1,0].set_title('Precision')
axs[1,0].legend()
# Recall
axs[1,1].plot(history.history['recall'], label='Train Recall')
axs[1,1].plot(history.history['val_recall'], label='Val Recall')
axs[1,1].set_title('Recall')
axs[1,1].legend()
plt.tight_layout()
plt.show()
plot_history(history)
b. Evaluate on Test Set
# Make predictions
y_pred_prob = model.predict(X_test).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
# Calculate 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)
roc_auc = roc_auc_score(y_test, y_pred_prob)
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Test Precision: {precision:.4f}")
print(f"Test Recall: {recall:.4f}")
print(f"Test F1 Score: {f1:.4f}")
print(f"Test ROC-AUC: {roc_auc:.4f}")
# Classification Report
print("\nClassification Report:\n", classification_report(y_test, y_pred))
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Legitimate', 'Phishing'], yticklabels=['Legitimate', 'Phishing'])
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title('Confusion Matrix')
plt.show()
c. Plot ROC Curve
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)
plt.figure(figsize=(8,6))
plt.plot(fpr, tpr, label=f'ROC curve (area = {roc_auc:.4f})')
plt.plot([0,1], [0,1], 'k--') # Random classifier
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc='lower right')
plt.show()
4. Fine-Tuning and Further Optimizations
To achieve the best performance, consider the following additional strategies:
a. Cross-Validation
Implement K-Fold Cross-Validation to ensure the model's robustness.
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
fold = 1
metrics = {'accuracy': [], 'precision': [], 'recall': [], 'f1': [], 'roc_auc': []}
for train_index, val_index in skf.split(X_train, y_train):
print(f"Training fold {fold}...")
X_tr, X_val = X_train[train_index], X_train[val_index]
y_tr, y_val = y_train[train_index], y_train[val_index]
# Rebuild the model for each fold
model = tuner.hypermodel.build(best_hps)
history = model.fit(
X_tr, y_tr,
epochs=200,
validation_data=(X_val, y_val),
callbacks=callbacks,
class_weight=class_weights,
batch_size=batch_size,
verbose=0
)
# Evaluate
y_val_pred_prob = model.predict(X_val).ravel()
y_val_pred = (y_val_pred_prob >= 0.5).astype(int)
accuracy = accuracy_score(y_val, y_val_pred)
precision = precision_score(y_val, y_val_pred)
recall = recall_score(y_val, y_val_pred)
f1 = f1_score(y_val, y_val_pred)
roc_auc = roc_auc_score(y_val, y_val_pred_prob)
metrics['accuracy'].append(accuracy)
metrics['precision'].append(precision)
metrics['recall'].append(recall)
metrics['f1'].append(f1)
metrics['roc_auc'].append(roc_auc)
print(f"Fold {fold} - Accuracy: {accuracy:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f}, F1: {f1:.4f}, ROC-AUC: {roc_auc:.4f}")
fold += 1
print("\nCross-Validation Metrics:")
for metric in metrics:
print(f"{metric.capitalize()}: {np.mean(metrics[metric]):.4f} ± {np.std(metrics[metric]):.4f}")
b. Ensemble Methods
Combine predictions from multiple models to improve performance.
from tensorflow.keras.models import clone_model
# Assume we train multiple models (e.g., 3) and average their predictions
ensemble_models = []
num_models = 3
for i in range(num_models):
print(f"Training ensemble model {i+1}...")
model = tuner.hypermodel.build(best_hps)
model.fit(
X_train, y_train,
epochs=200,
validation_split=0.2,
callbacks=callbacks,
class_weight=class_weights,
batch_size=batch_size,
verbose=0
)
ensemble_models.append(model)
# Make ensemble predictions
y_pred_probs = [model.predict(X_test).ravel() for model in ensemble_models]
y_pred_prob_avg = np.mean(y_pred_probs, axis=0)
y_pred_ensemble = (y_pred_prob_avg >= 0.5).astype(int)
# Evaluate ensemble
accuracy = accuracy_score(y_test, y_pred_ensemble)
precision = precision_score(y_test, y_pred_ensemble)
recall = recall_score(y_test, y_pred_ensemble)
f1 = f1_score(y_test, y_pred_ensemble)
roc_auc = roc_auc_score(y_test, y_pred_prob_avg)
print(f"\nEnsemble Model Performance:")
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"ROC-AUC: {roc_auc:.4f}")
c. Feature Engineering
Consider creating new features or selecting the most important ones to improve model performance. Techniques such as Recursive Feature Elimination (RFE) or feature importance from tree-based models can guide feature selection. However, when using CNNs, feature interactions are implicitly learned, so elaborate feature engineering might not be as critical.
d. Regularization Techniques
- Dropout: Already implemented in the model to prevent overfitting.
- L2 Regularization: Can be added to convolutional and dense layers.
from tensorflow.keras.regularizers import l2
# Example of adding L2 regularization to Conv1D layers
model.add(Conv1D(
filters=best_hps.get('filters_1'),
kernel_size=best_hps.get('kernel_size_1'),
activation='relu',
kernel_regularizer=l2(0.001),
input_shape=(X_train.shape[1], X_train.shape[2])
))
e. Learning Rate Schedules
Use learning rate schedulers to adjust the learning rate during training, allowing the model to converge more effectively.
Already implemented ReduceLROnPlateau in callbacks.
f. Advanced Optimizers
While Adam is effective, experimenting with other optimizers like RAdam, Lookahead, or Nadam may yield better results.
from tensorflow.keras.optimizers import Nadam
# Example replacement in model compilation
model.compile(
optimizer=Nadam(learning_rate=best_hps.get('learning_rate')),
loss='binary_crossentropy',
metrics=['accuracy', tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.AUC()]
)
5. Final Recommendations
- Model Complexity: Ensure the model isn't too complex to prevent overfitting, especially given the number of features.
- Early Stopping: Prevents overfitting by stopping training when validation performance stops improving.
- Class Weights: Handle any potential class imbalance to ensure the model doesn't bias towards the majority class.
- Evaluation Metrics: Use a combination of metrics (precision, recall, F1-score, ROC-AUC) to comprehensively evaluate model performance, especially in imbalanced datasets.
By following the above steps and continuously iterating based on model performance, you can develop a robust CNN model optimized for phishing URL detection.