Certainly! Below is the complete, adjusted, and optimized code for your Convolutional Neural Network (CNN) model. This implementation incorporates the new data split of 70% training, 15% validation, and 15% testing. Additionally, the model architecture has been enhanced to potentially improve performance. The code is structured to be fully replicable.
import tensorflow as tf
import keras_tuner as kt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import os
# Set seeds for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Ensure TensorFlow uses deterministic operations (optional, may impact performance)
os.environ['TF_CUDNN_DETERMINISTIC'] = '1'
# Read data
df = 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 = df[features]
# Handle missing values by replacing them with zero
X.fillna(0, inplace=True)
# Feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Reshape for Conv1D: (samples, timesteps, features)
X_reshaped = np.expand_dims(X_scaled, axis=2) # Shape: (n_samples, n_features, 1)
# Encode labels to binary values (0/1)
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(df['status']) # Assuming 'status' has two classes
# Split data into 70% train and 30% temp (validation + test)
X_train, X_temp, y_train, y_temp = train_test_split(
X_reshaped, y, test_size=0.3, random_state=42, stratify=y
)
# Split temp into 50% validation and 50% test (15% each of the original data)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp
)
print(f"Training set shape: {X_train.shape}, Training labels shape: {y_train.shape}")
print(f"Validation set shape: {X_val.shape}, Validation labels shape: {y_val.shape}")
print(f"Test set shape: {X_test.shape}, Test labels shape: {y_test.shape}")
def model_builder(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=[3, 5, 7]),
activation='relu',
input_shape=(X_reshaped.shape[1], 1),
kernel_regularizer=l2(hp.Float('l2_1', min_value=1e-5, max_value=1e-3, sampling='LOG'))
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(rate=hp.Float('dropout_1', min_value=0.2, max_value=0.5, step=0.1)))
# Second Conv1D layer
model.add(Conv1D(
filters=hp.Int('filters_2', min_value=64, max_value=256, step=64),
kernel_size=hp.Choice('kernel_size_2', values=[3, 5, 7]),
activation='relu',
kernel_regularizer=l2(hp.Float('l2_2', min_value=1e-5, max_value=1e-3, sampling='LOG'))
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(rate=hp.Float('dropout_2', min_value=0.2, max_value=0.5, step=0.1)))
# Third Conv1D layer (optional for deeper models)
model.add(Conv1D(
filters=hp.Int('filters_3', min_value=64, max_value=256, step=64),
kernel_size=hp.Choice('kernel_size_3', values=[3, 5]),
activation='relu',
kernel_regularizer=l2(hp.Float('l2_3', min_value=1e-5, max_value=1e-3, sampling='LOG'))
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(rate=hp.Float('dropout_3', min_value=0.2, max_value=0.5, step=0.1)))
# Flatten and Dense layers
model.add(Flatten())
model.add(Dense(
units=hp.Int('dense_units', min_value=64, max_value=256, step=64),
activation='relu',
kernel_regularizer=l2(hp.Float('dense_l2', min_value=1e-5, max_value=1e-3, sampling='LOG'))
))
model.add(BatchNormalization())
model.add(Dropout(rate=hp.Float('dropout_dense', min_value=0.2, max_value=0.5, step=0.1)))
# Output layer
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(
optimizer=Adam(
learning_rate=hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
),
loss='binary_crossentropy',
metrics=['accuracy']
)
return model
# Instantiate the Hyperband tuner
tuner = kt.Hyperband(
model_builder,
objective='val_accuracy',
max_epochs=50,
factor=3,
directory='my_dir',
project_name='phishing_cnn_tuning',
overwrite=True
)
# Define early stopping to prevent overfitting during hyperparameter search
stop_early = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
# Optionally, define a model checkpoint to save the best model during tuning
checkpoint_path = 'best_model.h5'
checkpoint = ModelCheckpoint(
filepath=checkpoint_path,
monitor='val_accuracy',
save_best_only=True,
mode='max'
)
# Perform hyperparameter search using the training and validation sets
tuner.search(
X_train, y_train,
epochs=100,
validation_data=(X_val, y_val),
callbacks=[stop_early, checkpoint],
batch_size=hp.Int('batch_size', 16, 128, step=16) # Optional: include batch_size in hyperparameters
)
# Retrieve the best hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete. Here are the optimal hyperparameters:
- Filters in first Conv1D layer: {best_hps.get('filters_1')}
- Kernel size in first Conv1D layer: {best_hps.get('kernel_size_1')}
- L2 regularization in first Conv1D layer: {best_hps.get('l2_1')}
- Dropout rate after first Conv1D layer: {best_hps.get('dropout_1')}
- Filters in second Conv1D layer: {best_hps.get('filters_2')}
- Kernel size in second Conv1D layer: {best_hps.get('kernel_size_2')}
- L2 regularization in second Conv1D layer: {best_hps.get('l2_2')}
- Dropout rate after second Conv1D layer: {best_hps.get('dropout_2')}
- Filters in third Conv1D layer: {best_hps.get('filters_3')}
- Kernel size in third Conv1D layer: {best_hps.get('kernel_size_3')}
- L2 regularization in third Conv1D layer: {best_hps.get('l2_3')}
- Dropout rate after third Conv1D layer: {best_hps.get('dropout_3')}
- Units in Dense layer: {best_hps.get('dense_units')}
- L2 regularization in Dense layer: {best_hps.get('dense_l2')}
- Dropout rate after Dense layer: {best_hps.get('dropout_dense')}
- Learning rate: {best_hps.get('learning_rate')}
- Batch size: {best_hps.get('batch_size')}
""")
# Build the model with the optimal hyperparameters
model = tuner.hypermodel.build(best_hps)
# Define callbacks for training
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
model_checkpoint = ModelCheckpoint(
filepath='best_model_final.h5',
monitor='val_accuracy',
save_best_only=True,
mode='max'
)
# Train the model using the training set and validate on the validation set
history = model.fit(
X_train, y_train,
epochs=200,
validation_data=(X_val, y_val),
callbacks=[early_stop, model_checkpoint],
batch_size=best_hps.get('batch_size'),
verbose=1
)
# Load the best model
model.load_weights('best_model_final.h5')
# Evaluate the model on the test set
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"\nTest Accuracy: {test_accuracy:.4f}")
print(f"Test Loss: {test_loss:.4f}")
# Predict the labels for X_test
y_pred_prob = model.predict(X_test)
y_pred = (y_pred_prob > 0.5).astype(int).flatten()
# Detailed classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred, digits=4))
# Confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
# Plot learning curves
plt.figure(figsize=(14, 6))
# Accuracy plot
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('Training and Validation Accuracy')
plt.xlabel('Epochs')
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('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Plot Confusion Matrix
import seaborn as sns
plt.figure(figsize=(6, 5))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
Explanation of Adjustments and Enhancements
-
Data Splitting:
- Training Set: 70%
- Validation Set: 15%
- Test Set: 15%
The data is first split into 70% training and 30% temporary (temp) sets. The temporary set is then further split equally into 15% validation and 15% test sets. Stratification is used to maintain the class distribution across splits.
-
Model Enhancements:
- Additional Conv1D Layer: A third Conv1D layer has been added to capture more complex patterns in the data.
- Batch Normalization: Added after each Conv1D and Dense layer to stabilize and accelerate training.
- Hyperparameter Tuning:
- Kernel Sizes: Expanded choices to include 7 for more flexibility.
- L2 Regularization: Tuned as a hyperparameter to prevent overfitting.
- Dropout Rates: Increased the minimum dropout rate to 0.2 to enhance regularization.
- Batch Size: Included as a hyperparameter to optimize training efficiency.
- Learning Rate and Batch Size: These are now hyperparameters being tuned to find the optimal values.
- Callbacks:
- Early Stopping: Increased patience to 10 to allow the model more epochs to converge during both hyperparameter tuning and final training.
- Model Checkpointing: Saves the best model based on validation accuracy.
- Hyperband Tuner Settings: Increased
max_epochs to 50 to allow sufficient exploration during hyperparameter tuning.
-
Evaluation Metrics:
- Detailed Classification Report: Provides precision, recall, f1-score, and support with four decimal places.
- Confusion Matrix: Added to visualize the performance in terms of true positives, false positives, true negatives, and false negatives.
-
Plot Enhancements:
- Learning Curves: Plots for both accuracy and loss during training to monitor overfitting and convergence.
- Confusion Matrix Heatmap: A visual representation using Seaborn for better interpretability.
-
Notes for Replicability
Final Thoughts
This enhanced implementation should provide a more robust and potentially higher-performing model for phishing detection. The additional layers, batch normalization, and comprehensive hyperparameter tuning contribute to the model's ability to generalize better on unseen data. Always ensure to monitor overfitting and adjust hyperparameters or model complexity accordingly.