Help me come up with the code to do CNN using the same style as this MLP way of doing.
My MLP code:
Import packages
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! Transitioning from a Multi-Layer Perceptron (MLP) to a Convolutional Neural Network (CNN) involves several key changes, especially since CNNs are typically used for data with spatial or sequential structure. However, you can adapt CNNs for tabular data like your phishing dataset by treating the input features as a 1D sequence.
Below is a comprehensive guide and code example that mirrors your existing MLP workflow but utilizes a CNN implemented with TensorFlow and Keras.
Overview of Changes
Library Imports: Introduce TensorFlow and Keras for building and training the CNN model.
Data Preprocessing: Perform similar scaling and encoding as in the MLP approach.
Handling Class Imbalance: Continue using SMOTE for oversampling the minority class.
Model Building: Define a 1D CNN architecture suitable for tabular data.
Hyperparameter Tuning: Use Keras' GridSearchCV wrapper to perform hyperparameter tuning.
Evaluation: Assess the model using the same metrics and visualization techniques.
Detailed Code Example
python
# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Scikit-learn imports
from sklearn.feature_selection import VarianceThreshold
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LassoCV
from sklearn.model_selection import train_test_split, GridSearchCV
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
)
# Imbalanced-learn imports
from imblearn.over_sampling import SMOTE
# TensorFlow and Keras imports
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv1D, GlobalMaxPooling1D, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.optimizers import Adam, SGD
# Suppress TensorFlow warnings for cleaner output
import logging
logging.getLogger('tensorflow').setLevel(logging.ERROR)
# 1. Load and preprocess the data
# --------------------------------
# Read the dataset
df = pd.read_csv('dataset_phishing.csv')
# Define feature columns
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].values
y = df['status'].values
# Scale the features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Encode the labels
le = LabelEncoder()
y_encoded = le.fit_transform(y)
# 2. Split the data into training, validation, and test sets
# ----------------------------------------------------------
# Step 1: Split data into 70% train and 30% temp (validation + test)
X_train, X_temp, y_train, y_temp = train_test_split(
X_scaled, y_encoded, test_size=0.3, random_state=42, stratify=y_encoded
)
# 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.5, random_state=42, stratify=y_temp
)
# 3. Handle class imbalance using SMOTE
# -------------------------------------
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
# 4. Reshape data for CNN input
# -----------------------------
# CNNs expect data with shape (samples, timesteps, features)
# For 1D CNN on tabular data, we can treat each feature as a timestep with 1 feature
X_resampled_cnn = X_resampled.reshape((X_resampled.shape[0], X_resampled.shape[1], 1))
X_val_cnn = X_val.reshape((X_val.shape[0], X_val.shape[1], 1))
X_test_cnn = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
# 5. Define the CNN model creation function
# ------------------------------------------
def create_cnn_model(
num_filters=32, kernel_size=3, dropout_rate=0.5,
activation='relu', optimizer='adam'
):
model = Sequential()
model.add(Conv1D(filters=num_filters, kernel_size=kernel_size, activation=activation, input_shape=(X_resampled_cnn.shape[1], 1)))
model.add(GlobalMaxPooling1D())
model.add(Dropout(dropout_rate))
model.add(Dense(64, activation=activation))
model.add(Dropout(dropout_rate))
model.add(Dense(1, activation='sigmoid'))
model.compile(
loss='binary_crossentropy',
optimizer=optimizer,
metrics=['accuracy']
)
return model
# 6. Wrap the model for use in scikit-learn
# -----------------------------------------
cnn_classifier = KerasClassifier(build_fn=create_cnn_model, verbose=0)
# 7. Define the hyperparameter grid for GridSearchCV
# ---------------------------------------------------
param_grid = {
'num_filters': [32, 64],
'kernel_size': [3, 5],
'dropout_rate': [0.3, 0.5],
'activation': ['relu', 'tanh'],
'optimizer': ['adam', 'sgd'],
'batch_size': [32, 64],
'epochs': [50] # You can increase epochs and use callbacks for early stopping
}
# 8. Set up GridSearchCV
# ----------------------
grid = GridSearchCV(
estimator=cnn_classifier,
param_grid=param_grid,
cv=3, # 3-fold cross-validation
scoring='recall', # Since phishing detection may require high recall
verbose=2,
n_jobs=1 # Due to the computational intensity of training CNNs
)
# 9. Fit the GridSearchCV
# -----------------------
grid_result = grid.fit(X_resampled_cnn, y_resampled)
# 10. Retrieve the best model and its parameters
# ---------------------------------------------
print(f"Best Hyperparameters: {grid_result.best_params_}")
best_model = grid_result.best_estimator_.model
# 11. Evaluate the model on the validation set
# --------------------------------------------
# Predict on validation set
y_val_pred_prob = best_model.predict(X_val_cnn).ravel()
y_val_pred = (y_val_pred_prob >= 0.5).astype(int)
# Compute evaluation metrics
val_accuracy = accuracy_score(y_val, y_val_pred)
val_precision = precision_score(y_val, y_val_pred)
val_recall = recall_score(y_val, y_val_pred)
val_f1 = f1_score(y_val, y_val_pred)
val_roc_auc = roc_auc_score(y_val, y_val_pred_prob)
# Print evaluation metrics
print("\nValidation Set Metrics:")
print(f"Accuracy: {val_accuracy:.4f}")
print(f"Precision: {val_precision:.4f}")
print(f"Recall: {val_recall:.4f}")
print(f"F1 Score: {val_f1:.4f}")
print(f"ROC AUC Score: {val_roc_auc:.4f}")
# Confusion Matrix for validation set
val_conf_matrix = confusion_matrix(y_val, y_val_pred)
plt.figure(figsize=(6,4))
sns.heatmap(val_conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (Validation Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
# Classification Report for validation set
print("Classification Report (Validation Set):\n", classification_report(y_val, y_val_pred))
# 12. Evaluate the model on the test set
# --------------------------------------
# Predict on test set
y_test_pred_prob = best_model.predict(X_test_cnn).ravel()
y_test_pred = (y_test_pred_prob >= 0.5).astype(int)
# Compute evaluation metrics
test_accuracy = accuracy_score(y_test, y_test_pred)
test_precision = precision_score(y_test, y_test_pred)
test_recall = recall_score(y_test, y_test_pred)
test_f1 = f1_score(y_test, y_test_pred)
test_roc_auc = roc_auc_score(y_test, y_test_pred_prob)
# Print evaluation metrics
print("\nTest Set Metrics:")
print(f"Accuracy: {test_accuracy:.4f}")
print(f"Precision: {test_precision:.4f}")
print(f"Recall: {test_recall:.4f}")
print(f"F1 Score: {test_f1:.4f}")
print(f"ROC AUC Score: {test_roc_auc:.4f}")
# Confusion Matrix for test set
test_conf_matrix = confusion_matrix(y_test, y_test_pred)
plt.figure(figsize=(6,4))
sns.heatmap(test_conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix (Test Set)')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
# Classification Report for test set
print("Classification Report (Test Set):\n", classification_report(y_test, y_test_pred))
Explanation of the Steps
Library Imports: In addition to your existing libraries, TensorFlow and Keras are imported for building the CNN. The KerasClassifier wrapper allows integration with Scikit-learn's GridSearchCV.
Data Preprocessing:
Scaling: StandardScaler is used to standardize the features.
Encoding: LabelEncoder transforms the target labels into binary format.
Reshaping: CNNs expect input data with shape (samples, timesteps, features). Here, each feature is treated as a timestep with one feature, resulting in a shape of (samples, number_of_features, 1).
Handling Imbalance: SMOTE is applied to the training data to oversample the minority class, ensuring that the model has sufficient examples to learn from.
Model Building:
A function create_cnn_model defines the CNN architecture, including convolutional layers, pooling, dropout for regularization, and dense layers for classification.
The model uses the binary_crossentropy loss function and is compiled with an optimizer chosen from the hyperparameter grid.
Hyperparameter Tuning:
GridSearchCV explores different combinations of hyperparameters such as the number of filters, kernel size, dropout rate, activation functions, and optimizers.
Due to the computational intensity of CNNs, it's recommended to limit the number of parameters and possibly use fewer cross-validation folds if resources are constrained.
Model Evaluation:
After training, the best model is evaluated on both the validation and test sets.
Metrics such as Accuracy, Precision, Recall, F1 Score, and ROC AUC are computed.
Confusion matrices and classification reports provide detailed insights into the model's performance.
Additional Recommendations
Early Stopping: To prevent overfitting and reduce training time, consider implementing early stopping using Keras callbacks. This will halt training when the model's performance on a validation set stops improving.
python
from tensorflow.keras.callbacks import EarlyStopping
early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
Modify the create_cnn_model function to include callbacks during training.
Batch Normalization: Adding batch normalization layers can help stabilize and accelerate the training process.
Learning Rate Scheduling: Implementing learning rate schedules or using adaptive optimizers can lead to better convergence.
Model Complexity: Adjust the complexity of your CNN based on the dataset size. For smaller datasets, simpler models may perform better to avoid overfitting.
Alternative Models: While CNNs can be adapted for tabular data, models like Gradient Boosting (e.g., XGBoost, LightGBM) often perform exceptionally well on such datasets and might be worth exploring.
Conclusion
The above code provides a structured approach to implementing a CNN for your phishing dataset, mirroring the steps you took with your MLP. By following this template, you can experiment with different model architectures and hyperparameters to optimize performance for your specific use case. Remember to monitor for overfitting and adjust the model complexity and regularization techniques accordingly.