# 1D CNN for Phishing Detection Using Selected Features
# Import packages
import pandas as pd
import numpy as np
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)
from sklearn.utils.class_weight import compute_class_weight
from imblearn.over_sampling import SMOTE
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, GlobalMaxPooling1D, Dense, Dropout
from tensorflow.keras.optimizers import Adam, SGD
import seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
import warnings
warnings.filterwarnings('ignore')
# Set random seed for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Read data
df = pd.read_csv('dataset_phishing.csv')
# Define selected features
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
# Encode labels
le = LabelEncoder()
y = le.fit_transform(y)
# Scale the features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Reshape for Conv1D (samples, steps, features)
# Here, each feature is treated as a "step" with 1 feature per step
X_scaled_reshaped = X_scaled.reshape((X_scaled.shape[0], X_scaled.shape[1], 1))
# 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_reshaped, y, test_size=0.3, random_state=42, 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.5, random_state=42, stratify=y_temp)
# Handle class imbalance by oversampling the minority class (SMOTE)
# Note: SMOTE might not work directly with 3D data; reshape to 2D, apply SMOTE, then reshape back
X_train_2d = X_train.reshape((X_train.shape[0], X_train.shape[1]))
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_train_2d, y_train)
X_resampled = X_resampled.reshape((X_resampled.shape[0], X_resampled.shape[1], 1))
# Compute class weights
class_weights = compute_class_weight('balanced', classes=np.unique(y_resampled), y=y_resampled)
class_weights_dict = dict(enumerate(class_weights))
# Define a function to create the 1D CNN model
def create_1d_cnn_model(activation='relu', optimizer='adam', learning_rate=0.001, dropout_rate=0.5):
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation=activation, input_shape=(X_train.shape[1],1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=128, kernel_size=3, activation=activation))
model.add(GlobalMaxPooling1D())
model.add(Dense(64, activation=activation))
model.add(Dropout(dropout_rate))
model.add(Dense(1, activation='sigmoid'))
if optimizer == 'adam':
opt = Adam(learning_rate=learning_rate)
elif optimizer == 'sgd':
opt = SGD(learning_rate=learning_rate)
else:
opt = Adam(learning_rate=learning_rate)
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])
return model
# Wrap the model using KerasClassifier
model = KerasClassifier(build_fn=create_1d_cnn_model, verbose=0)
# Define hyperparameter grid
param_grid = {
'activation': ['relu', 'tanh'],
'optimizer': ['adam', 'sgd'],
'learning_rate': [0.001, 0.01],
'dropout_rate': [0.3, 0.5],
'epochs': [20, 30],
'batch_size': [128, 256]
}
# Setup GridSearchCV
grid = GridSearchCV(estimator=model, param_grid=param_grid,
cv=3, scoring='recall', verbose=2, n_jobs=-1)
# Fit the grid search to the resampled training data
grid_result = grid.fit(X_resampled, y_resampled,
class_weight=class_weights_dict,
validation_data=(X_val, y_val))
# Get the best model
best_cnn = grid_result.best_estimator_.model
# Evaluate on validation set
y_val_pred_prob = best_cnn.predict(X_val).flatten()
y_val_pred = (y_val_pred_prob > 0.5).astype(int)
# Calculate performance metrics for the validation set
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 for the validation set
print("Validation 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)
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))
# Evaluate on test set
y_test_pred_prob = best_cnn.predict(X_test).flatten()
y_test_pred = (y_test_pred_prob > 0.5).astype(int)
# Calculate performance metrics for the test set
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 for the test set
print("Test 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)
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))