Certainly! Below is an enhanced version of your Character-Level CNN model for phishing URL detection. This improved implementation includes additional metrics such as Precision, Recall, F1-Score, and ROC-AUC. It also incorporates comprehensive visualizations, including training history plots, confusion matrix heatmaps, and ROC curves, which are essential for analyzing model performance in your journal.
Key Enhancements:
-
Model Architecture Improvements:
- Batch Normalization: Added after convolutional layers to stabilize and accelerate training.
- Additional Convolutional Layers: Increased model depth for better feature extraction.
- Activation Functions: Implemented Leaky ReLU to allow a small gradient when the unit is not active.
-
Metrics:
- Precision, Recall, F1-Score: Provides a better understanding of the model's performance, especially in classification tasks.
- ROC-AUC: Measures the ability of the model to distinguish between classes.
-
Visualizations:
- Training History: Plots for loss and accuracy over epochs.
- Confusion Matrix: Heatmap visualization for better interpretability.
- ROC Curve: Visual representation of the trade-off between true positive rate and false positive rate.
-
Additional Improvements:
- Early Stopping and Model Checkpointing: Enhanced callback mechanisms for better training control.
- Stratified Splitting: Ensures that the train and test sets have the same distribution of classes.
Complete Enhanced Code:
# Import necessary packages
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, StratifiedKFold
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import (classification_report, confusion_matrix,
roc_curve, auc, precision_recall_fscore_support)
from imblearn.over_sampling import SMOTE # Install using `pip install imblearn`
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (Conv1D, MaxPooling1D, Flatten, Dense,
Dropout, BatchNormalization, LeakyReLU)
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
# Set random seeds for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Read data
data = 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 = data[features]
y = data['status'] # 'status' column: 1 for phishing, 0 for legitimate
# Handle missing values
X.fillna(0, inplace=True)
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# Check class distribution
print("Original class distribution:")
print(pd.Series(y_encoded).value_counts())
# Handle class imbalance using SMOTE (if necessary)
# Since the dataset is already balanced (50/50), SMOTE is optional
# Here, it's used as per the initial implementation
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X, y_encoded)
# Verify resampled class distribution
print("\nResampled class distribution:")
print(pd.Series(y_resampled).value_counts())
# Scale features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_resampled)
# Reshape data for Conv1D
X_reshaped = np.expand_dims(X_scaled, axis=2)
# Split data into training and test sets with stratification
X_train, X_test, y_train, y_test = train_test_split(
X_reshaped, y_resampled, test_size=0.2, random_state=42, stratify=y_resampled)
print(f"\nTraining samples: {X_train.shape[0]}, Testing samples: {X_test.shape[0]}")
# Define improved CNN model architecture
def build_model(input_shape):
model = Sequential()
# First Conv Block
model.add(Conv1D(filters=64, kernel_size=3, input_shape=input_shape))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.1))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Second Conv Block
model.add(Conv1D(filters=128, kernel_size=3))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.1))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Third Conv Block
model.add(Conv1D(filters=256, kernel_size=3))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.1))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Flatten and Dense Layers
model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=0.1))
model.add(Dropout(0.4))
# Output Layer
model.add(Dense(1, activation='sigmoid'))
return model
# Build the model
input_shape = (X_reshaped.shape[1], X_reshaped.shape[2])
model = build_model(input_shape)
# Compile the model
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy',
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall')])
# Define callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1, restore_best_weights=True)
model_checkpoint = ModelCheckpoint('best_model_improved.h5',
monitor='val_accuracy',
save_best_only=True,
verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1)
# Train the model
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=64,
validation_data=(X_test, y_test),
callbacks=[early_stopping, model_checkpoint, reduce_lr],
verbose=1
)
# Plot Training History
def plot_history(history):
# Accuracy Plot
plt.figure(figsize=(14, 5))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy', marker='o')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy', marker='o')
plt.title('Accuracy over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
# Loss Plot
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss', marker='o')
plt.plot(history.history['val_loss'], label='Validation Loss', marker='o')
plt.title('Loss over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
plot_history(history)
# Load the best saved model
model.load_weights('best_model_improved.h5')
# Evaluate the model
loss, accuracy, precision, recall = model.evaluate(X_test, y_test, verbose=0)
f1_score = 2 * (precision * recall) / (precision + recall + 1e-7) # Avoid division by zero
print(f"\nTest Loss: {loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Test Precision: {precision:.4f}")
print(f"Test Recall: {recall:.4f}")
print(f"Test F1-Score: {f1_score:.4f}")
# Predict probabilities and classes on test data
y_pred_prob = model.predict(X_test).ravel()
y_pred = (y_pred_prob > 0.5).astype(int)
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=['Legitimate', 'Phishing']))
# Confusion Matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
# Plot Confusion Matrix
def plot_confusion_matrix(cm, class_names):
plt.figure(figsize=(6,5))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=class_names, yticklabels=class_names)
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title('Confusion Matrix')
plt.show()
plot_confusion_matrix(conf_matrix, ['Legitimate', 'Phishing'])
# Compute ROC Curve and AUC
fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)
roc_auc = auc(fpr, tpr)
# Plot ROC Curve
def plot_roc_curve(fpr, tpr, roc_auc):
plt.figure(figsize=(8,6))
plt.plot(fpr, tpr, color='darkorange', label=f'ROC curve (AUC = {roc_auc:.4f})')
plt.plot([0,1], [0,1], color='navy', linestyle='--')
plt.xlim([0.0,1.0])
plt.ylim([0.0,1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()
plot_roc_curve(fpr, tpr, roc_auc)
# Additional Metrics: Precision, Recall, F1-Score for each class
precision_cls, recall_cls, f1_cls, _ = precision_recall_fscore_support(y_test, y_pred)
metrics_df = pd.DataFrame({
'Class': ['Legitimate', 'Phishing'],
'Precision': precision_cls,
'Recall': recall_cls,
'F1-Score': f1_cls
})
print("\nDetailed Metrics per Class:")
print(metrics_df)
# Save metrics and plots if needed
# For example:
# metrics_df.to_csv('model_metrics.csv', index=False)
# plt.savefig('confusion_matrix.png')
# plt.savefig('roc_curve.png')
# plt.savefig('training_history.png')
Explanation of Enhancements:
-
Model Architecture:
- BatchNormalization: This layer normalizes the activations of the previous layer at each batch, i.e., applies a transformation that maintains the mean output close to 0 and the output standard deviation close to 1.
- LeakyReLU Activation: Unlike the standard ReLU, LeakyReLU allows a small, non-zero gradient when the unit is not active, which helps in mitigating the dying ReLU problem.
- Additional Conv Layers: Adding more convolutional layers can help the model capture more complex patterns in the data.
-
Callbacks:
- ReduceLROnPlateau: Reduces the learning rate when a metric has stopped improving, which can lead to better convergence.
-
Evaluation Metrics:
- F1-Score: The harmonic mean of Precision and Recall, providing a balance between the two.
- ROC-AUC: A single scalar value to summarize the performance of the model across all classification thresholds.
-
Visualizations:
- Training History: Helps in understanding if the model is overfitting or underfitting.
- Confusion Matrix: A heatmap makes it easier to visualize the performance of the classification model.
- ROC Curve: Visualizes the trade-off between the true positive rate and false positive rate.
-
Code Organization:
- Functions like
plot_history, plot_confusion_matrix, and plot_roc_curve help in keeping the code clean and reusable.
- Detailed print statements provide clear insights into each step's outcomes.
-
Reproducibility:
- Setting random seeds ensures that the results can be replicated.
Dependencies:
Ensure that you have the following packages installed. You can install any missing packages using pip:
pip install pandas numpy matplotlib seaborn scikit-learn imbalanced-learn tensorflow
Notes:
-
SMOTE Usage: Although your dataset is initially balanced, applying SMOTE can sometimes help in creating more robust models by introducing synthetic examples. However, it's essential to validate whether SMOTE improves performance in your specific case.
-
Hyperparameter Tuning: Further improvements can be achieved by tuning hyperparameters such as the number of filters, kernel sizes, dropout rates, learning rates, etc., possibly using techniques like Grid Search or Random Search.
-
Cross-Validation: Implementing Stratified K-Fold cross-validation can provide a more reliable estimate of the model's performance.
-
Feature Engineering: Explore adding or transforming features to enhance the model's ability to capture relevant patterns indicative of phishing URLs.
This comprehensive implementation should significantly enhance your model's performance and provide the necessary visualizations and metrics for your journal. Feel free to customize further based on your specific requirements and observations during experimentation.