Right now, I have a CNN model and a MLP model. Please adjust my CNN code such that it follows more closely to MLP in terms of using grid search, and making use of validation. So just change the model to CNN, but ensure the metrics used for optimizing is the same as MLP. Please make this results reproducible if run from another machine. Give me entire code.
My CNN Code now:
import os
import random
import numpy as np
import tensorflow as tf
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)
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
X = data[features]
y = data['status'] # 'status' is 'legitimate' or 'phishing'
Assistant
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)
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
history = best_model.fit(
X_train_cnn, y_train,
epochs=50,
validation_split=0.2,
callbacks=[early_stopping],
verbose=1
)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_selection import VarianceThreshold
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LassoCV
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)
Certainly! Below is the complete adjusted CNN code that aligns more closely with your MLP implementation. This version incorporates Grid Search-like hyperparameter tuning using Keras Tuner, utilizes a separate validation set, optimizes for the same metrics (specifically recall), handles class imbalance with SMOTE, and ensures reproducibility across different machines.
Key Adjustments:
Data Splitting: The dataset is split into training (70%), validation (15%), and testing (15%) sets to mirror the MLP approach.
Class Imbalance Handling: SMOTE is applied to the training set to address class imbalance.
Hyperparameter Optimization: Keras Tuner’s RandomSearch is configured to optimize for recall instead of accuracy.
Reproducibility: All random seeds and environment variables are set to ensure reproducible results.
Metrics Alignment: The model is compiled with recall as a metric and the tuner optimizes based on validation recall.
Here is the complete revised CNN code:
python
import os
import random
import numpy as np
import tensorflow as tf
# ===========================
# 1. Reproducibility Settings
# ===========================
# 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. Additional settings for TensorFlow reproducibility
# Note: Complete reproducibility might require setting additional environment variables and using specific TensorFlow configurations
# However, some non-deterministic operations may still affect reproducibility.
# ===========================
# 2. Import Required Packages
# ===========================
import pandas as pd
# For data preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import (
accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, classification_report,
confusion_matrix
)
# For handling class imbalance
from imblearn.over_sampling import SMOTE
# 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
from tensorflow.keras.metrics import Recall
# For hyperparameter tuning
import keras_tuner as kt
from keras_tuner.tuners import RandomSearch
# For visualization
import matplotlib.pyplot as plt
import seaborn as sns
# =============================================
# 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)
# =============================================
# 5. Data Splitting
# =============================================
# Step 1: Split data into 70% train and 30% temp (validation + test)
X_train, X_temp, y_train, y_temp = train_test_split(
X, y, test_size=0.30, random_state=seed, stratify=y
)
# Step 2: Split the temp set 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.50, random_state=seed, stratify=y_temp
)
print(f'Training set size: {X_train.shape[0]}')
print(f'Validation set size: {X_val.shape[0]}')
print(f'Test set size: {X_test.shape[0]}')
# =============================================
# 6. Handling Class Imbalance with SMOTE
# =============================================
smote = SMOTE(random_state=seed)
X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)
print(f'Resampled training set size: {X_train_resampled.shape[0]}')
print(f'Class distribution in resampled training set: {np.bincount(y_train_resampled)}')
# =============================================
# 7. Feature Scaling
# =============================================
scaler = StandardScaler()
# Fit on resampled training data
X_train_scaled = scaler.fit_transform(X_train_resampled)
# Transform validation and test data
X_val_scaled = scaler.transform(X_val)
X_test_scaled = scaler.transform(X_test)
# =============================================
# 8. Reshape Data for Conv1D
# =============================================
# Reshape data to be suitable for Conv1D (samples, timesteps, features)
# Each feature is treated as a timestep with 1 feature channel
X_train_cnn = X_train_scaled.reshape(-1, X_train_scaled.shape[1], 1)
X_val_cnn = X_val_scaled.reshape(-1, X_val_scaled.shape[1], 1)
X_test_cnn = X_test_scaled.reshape(-1, X_test_scaled.shape[1], 1)
# =============================================
# 9. 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(
rate=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(
rate=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(
rate=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
model.compile(
optimizer=Adam(
hp.Float('lr', min_value=1e-4, max_value=1e-2, sampling='LOG', default=1e-3)
),
loss='binary_crossentropy',
metrics=[Recall(name='recall')]
)
return model
# Initialize the tuner
tuner = RandomSearch(
build_model,
objective='val_recall',
max_trials=20,
executions_per_trial=1,
directory='tuning',
project_name='cnn_phishing',
seed=seed,
overwrite=True
)
# Early stopping callback to prevent overfitting
early_stopping = EarlyStopping(
monitor='val_loss',
patience=5,
restore_best_weights=True
)
# Run the hyperparameter search
tuner.search(
x=X_train_cnn,
y=y_train_resampled,
epochs=50,
validation_data=(X_val_cnn, y_val),
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')},
dropout rate is {best_hps.get('dropout_rate_1')},
and the learning rate is {best_hps.get('lr')}.
""")
if best_hps.get('second_conv_layer'):
print(f"The optimal number of filters in the second Conv1D layer is {best_hps.get('filters_2')}, "
f"kernel size is {best_hps.get('kernel_size_2')}, "
f"and dropout rate is {best_hps.get('dropout_rate_2')}.")
print(f"The optimal number of dense layers is {best_hps.get('num_dense_layers')}.")
for i in range(best_hps.get('num_dense_layers')):
print(f"Optimal units in dense layer {i+1}: {best_hps.get('units_{i}')}")
print(f"Optimal dropout rate in dense layer {i+1}: {best_hps.get('dropout_rate_dense_{i}')}")
# Build the model with the best hyperparameters
best_model = tuner.hypermodel.build(best_hps)
# Train the best model
history = best_model.fit(
X_train_cnn, y_train_resampled,
epochs=50,
validation_data=(X_val_cnn, y_val),
callbacks=[early_stopping],
verbose=1
)
# =============================================
# 10. Model Evaluation
# =============================================
# Evaluate the model on test data
test_loss, test_recall = best_model.evaluate(X_test_cnn, y_test, verbose=0)
print('Test Recall: {:.4f}'.format(test_recall))
# 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('Accuracy : {:.4f}'.format(accuracy))
print('Precision : {:.4f}'.format(precision))
print('Recall : {:.4f}'.format(recall))
print('F1 Score : {:.4f}'.format(f1))
print('ROC AUC : {:.4f}'.format(roc_auc))
print('\nConfusion Matrix:')
conf_matrix = confusion_matrix(y_test, y_pred)
print(conf_matrix)
# Plot Confusion Matrix
plt.figure(figsize=(6,4))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues',
xticklabels=['Legitimate', 'Phishing'],
yticklabels=['Legitimate', 'Phishing'])
plt.title('Confusion Matrix (Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
print('\nClassification Report:')
print(classification_report(y_test, y_pred, target_names=['Legitimate', 'Phishing']))
# =============================================
# 11. Reproducibility Note
# =============================================
print("\nTo ensure reproducibility on another machine, please make sure to:")
print("1. Use the same versions of all libraries mentioned above.")
print("2. Set the same random seed (currently set to 42).")
print("3. Ensure that the dataset 'dataset_phishing.csv' is identical.")
Explanation of Adjustments:
Reproducibility Settings:
All random seeds are set for Python’s built-in random module, NumPy, and TensorFlow to ensure reproducible results.
Note that complete reproducibility in TensorFlow may require additional settings, but the primary seeds are set.
Data Splitting:
The dataset is split into training (70%), validation (15%), and testing (15%) sets using train_test_split. Stratification ensures the class distribution remains consistent across splits.
Class Imbalance Handling with SMOTE:
SMOTE is applied only to the training set to oversample the minority class (phishing). This prevents data leakage into validation and test sets.
Feature Scaling:
StandardScaler is fitted on the resampled training data and then applied to validation and test sets to ensure consistent scaling.
Reshaping for Conv1D:
The data is reshaped to fit the input requirements of Conv1D layers, treating each feature as a timestep with one feature channel.
Model Building and Hyperparameter Tuning:
The build_model function defines the CNN architecture with hyperparameters that can be tuned.
Keras Tuner’s RandomSearch is configured to optimize for val_recall, aligning with the MLP’s focus on recall.
Early stopping is used to prevent overfitting during hyperparameter tuning and training.
Model Evaluation:
After training, the model is evaluated on the test set.
Key metrics such as Accuracy, Precision, Recall, F1 Score, and ROC AUC are calculated.
A confusion matrix and classification report provide detailed performance insights.
Visualization of the confusion matrix is included for better interpretability.
Reproducibility Note:
Instructions are provided at the end to ensure that others can reproduce the results by maintaining the same library versions, random seed, and dataset.
Additional Recommendations:
Library Versions: To ensure complete reproducibility, consider creating a requirements.txt file with exact library versions used in your environment.
Environment Management: Use environments (like virtualenv or conda) to manage dependencies and maintain consistency across different machines.
Saving Models and Results: For further reproducibility and analysis, consider saving the trained model and hyperparameter configurations.
python
# Save the best model
best_model.save('best_cnn_model.h5')
# Save the scaler
import joblib
joblib.dump(scaler, 'scaler.save')
# Save SMOTE object if needed
joblib.dump(smote, 'smote.save')
This adjusted CNN implementation should now closely mirror your MLP approach, ensuring consistency in hyperparameter tuning, validation usage, metric optimization, and reproducibility.