To modify your CNN model to optimize recall instead of accuracy and ensure reproducibility across different machines, you'll need to make several adjustments:
- Change the Optimization Objective: Configure the hyperparameter tuner to optimize for recall instead of accuracy.
- Include Recall as a Metric: Ensure that recall is calculated and monitored during training.
- Ensure Reproducibility: Maintain consistency in random operations across different machines by setting all relevant seeds and configuring TensorFlow for deterministic behavior.
Below is your adjusted implementation with detailed explanations for each change:
import os
import random
import numpy as np
import tensorflow as tf
# =============================================
# 1. Reproducibility Setup
# =============================================
# Define a seed value for reproducibility
seed = 42
# 1. Set the PYTHONHASHSEED environment variable for Python hash-based operations
os.environ['PYTHONHASHSEED'] = str(seed)
# 2. Set the Python built-in pseudo-random generator at a fixed value
random.seed(seed)
# 3. Set the NumPy pseudo-random generator at a fixed value
np.random.seed(seed)
# 4. Set the TensorFlow pseudo-random generator at a fixed value
tf.random.set_seed(seed)
# 5. Configure TensorFlow for deterministic operations (optional but recommended)
# Note: This may impact performance.
os.environ['TF_DETERMINISTIC_OPS'] = '1'
# =============================================
# 2. Import Required Packages
# =============================================
import pandas as pd
# For data preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# For performance metrics
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, classification_report,
confusion_matrix)
# For building the neural network
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.callbacks import EarlyStopping
# For hyperparameter tuning
import keras_tuner as kt
from keras_tuner.tuners import RandomSearch
# =============================================
# 3. Version Information (Optional)
# =============================================
print(f'TensorFlow version: {tf.__version__}')
print(f'Keras Tuner version: {kt.__version__}')
# =============================================
# 4. Data Loading and Preprocessing
# =============================================
# Read the dataset
data = pd.read_csv('dataset_phishing.csv')
# Define features and target variable
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' is 'legitimate' or 'phishing'
# Map the 'status' to numerical labels
label_mapping = {'legitimate': 0, 'phishing': 1}
y = y.map(label_mapping)
# Check for any unmapped values or missing values
if y.isnull().any():
print("Some 'status' values were not mapped properly. Please check the 'status' column for unexpected values.")
print(y[y.isnull()])
# Handle missing values in features if any
X.fillna(0, inplace=True)
# Split into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=seed, stratify=y)
# Standardize the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Reshape data to be suitable for Conv1D (samples, timesteps, features)
# Since we have numerical features, we treat each feature as a "time step"
X_train_cnn = X_train_scaled.reshape(-1, X_train_scaled.shape[1], 1)
X_test_cnn = X_test_scaled.reshape(-1, X_test_scaled.shape[1], 1)
# =============================================
# 5. Model Building and Hyperparameter Tuning
# =============================================
def build_model(hp):
model = Sequential()
# First Conv1D layer
model.add(Conv1D(
filters=hp.Int('filters_1', min_value=16, max_value=128, step=16),
kernel_size=hp.Int('kernel_size_1', min_value=2, max_value=5, step=1),
activation='relu',
input_shape=(X_train_cnn.shape[1], 1),
padding='same'
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(hp.Float('dropout_rate_1', min_value=0.0, max_value=0.5, step=0.1)))
# Optional second Conv1D layer
if hp.Boolean('second_conv_layer'):
model.add(Conv1D(
filters=hp.Int('filters_2', min_value=16, max_value=128, step=16),
kernel_size=hp.Int('kernel_size_2', min_value=2, max_value=5, step=1),
activation='relu',
padding='same'
))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(hp.Float('dropout_rate_2', min_value=0.0, max_value=0.5, step=0.1)))
model.add(Flatten())
# Dense 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(BatchNormalization())
model.add(Dropout(hp.Float(f'dropout_rate_dense_{i}', min_value=0.0, max_value=0.5, step=0.1)))
# Output layer
model.add(Dense(1, activation='sigmoid'))
# Compile the model with Recall as a metric
model.compile(
optimizer=Adam(
hp.Float('lr', min_value=1e-4, max_value=1e-2, sampling='LOG', default=1e-3)
),
loss='binary_crossentropy',
metrics=[
'accuracy',
tf.keras.metrics.Recall(name='recall') # Add Recall metric
]
)
return model
# Initialize the tuner to optimize for recall
tuner = RandomSearch(
build_model,
objective='val_recall', # Change objective to validation recall
max_trials=20,
executions_per_trial=1,
directory='tuning',
project_name='cnn',
seed=seed,
overwrite=True
)
# Early stopping callback to prevent overfitting
early_stopping = EarlyStopping(monitor='val_recall', patience=5,
restore_best_weights=True, mode='max')
# Run the hyperparameter search
tuner.search(
x=X_train_cnn,
y=y_train,
epochs=50, # Increased epochs to allow the model to converge
validation_split=0.2,
callbacks=[early_stopping],
verbose=1
)
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete.
The optimal number of filters in the first Conv1D layer is {best_hps.get('filters_1')},
kernel size is {best_hps.get('kernel_size_1')},
and the learning rate is {best_hps.get('lr')}.
""")
# Build the model with the best hyperparameters
best_model = tuner.hypermodel.build(best_hps)
# Train the best model with Early Stopping monitored on recall
history = best_model.fit(
X_train_cnn, y_train,
epochs=100, # Increased epochs for final training
validation_split=0.2,
callbacks=[early_stopping],
verbose=1
)
# =============================================
# 6. Model Evaluation
# =============================================
# Evaluate the model on test data
test_loss, test_acc, test_recall = best_model.evaluate(X_test_cnn, y_test)
print(f'Test Accuracy: {test_acc:.4f}')
print(f'Test Recall : {test_recall:.4f}')
# Predict probabilities and classes
y_pred_proba = best_model.predict(X_test_cnn).ravel()
y_pred = (y_pred_proba >= 0.5).astype(int)
# Calculate and print 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_proba)
print('\nModel Performance Metrics:')
print('--------------------------')
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}')
print('\nConfusion Matrix:')
print(confusion_matrix(y_test, y_pred))
print('\nClassification Report:')
print(classification_report(y_test, y_pred))
Detailed Explanation of Changes
-
Including Recall as a Metric in model.compile:
metrics=[
'accuracy',
tf.keras.metrics.Recall(name='recall') # Add Recall metric
]
- Purpose: This ensures that recall is tracked during training and validation, allowing the tuner to use it as the optimization objective.
- Note: Naming the metric explicitly as
'recall' helps in referencing it easily (e.g., 'val_recall').
-
Changing the Hyperparameter Tuner Objective to val_recall:
tuner = RandomSearch(
build_model,
objective='val_recall', # Change objective to validation recall
...
)
- Purpose: Directs the tuner to optimize for the validation recall rather than accuracy.
- Impact: The hyperparameter search will prioritize models that achieve higher recall on the validation set, potentially improving the model's ability to identify phishing instances.
-
Adjusting the Early Stopping Callback to Monitor val_recall:
early_stopping = EarlyStopping(monitor='val_recall', patience=5,
restore_best_weights=True, mode='max')
- Purpose: Stops training when the validation recall does not improve for a specified number of epochs (
patience=5), preventing overfitting.
- Parameter
mode='max': Indicates that training should stop when the monitored metric has stopped increasing.
-
Increasing the Number of Epochs:
epochs=50 # During tuning
...
epochs=100 # During final training
- Purpose: Provides the model with more opportunities to learn, especially since recall optimization might require more training iterations.
- Note: The exact number can be adjusted based on the dataset size and convergence behavior.
-
Ensuring Reproducibility:
-
Seed Setting: All sources of randomness (Python's random, NumPy's random generator, and TensorFlow's seeds) are set to a fixed value (seed = 42), ensuring consistent behavior across different runs and machines.
Additional Recommendations
-
Threshold Optimization:
The default classification threshold is 0.5, which might not be optimal for maximizing recall. You can explore adjusting the threshold based on the ROC curve or precision-recall curve to achieve better recall without substantially compromising other metrics.
from sklearn.metrics import precision_recall_curve
precision_vals, recall_vals, thresholds = precision_recall_curve(y_test, y_pred_proba)
# Choose a threshold that offers a good balance, e.g., maximum recall with acceptable precision
optimal_threshold = thresholds[np.argmax(recall_vals)]
y_pred_optimal = (y_pred_proba >= optimal_threshold).astype(int)
-
Class Imbalance Handling:
If your dataset is imbalanced (which is common in phishing detection), consider techniques such as:
- Class Weights: Adjust the loss function to give more weight to the minority class.
- Oversampling/Undersampling: Use methods like SMOTE to balance the dataset.
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced', classes=np.unique(y_train), y=y_train)
class_weights_dict = dict(enumerate(class_weights))
# Pass class_weights_dict to the `.fit()` method
history = best_model.fit(
X_train_cnn, y_train,
epochs=100,
validation_split=0.2,
callbacks=[early_stopping],
class_weight=class_weights_dict,
verbose=1
)
-
Cross-Validation:
Instead of a single train-validation split, use cross-validation to ensure that the model generalizes well across different subsets of the data.
Final Notes on Reproducibility
Despite setting all seeds and configuring TensorFlow for deterministic operations, absolute reproducibility across different hardware architectures (like CPUs vs. GPUs) or underlying drivers might still pose challenges. To mitigate this:
- Use the Same Hardware: Whenever possible, run experiments on identical hardware setups.
- Containerization: Utilize Docker containers to encapsulate your environment, ensuring consistency across different machines.
- Virtual Environments: Employ virtual environments (e.g.,
venv, conda) to manage dependencies precisely.
By implementing these changes and recommendations, your CNN model will prioritize recall during hyperparameter tuning and maintain higher consistency across different machines.