Certainly! I'll guide you through enhancing your current CNN-based phishing detection model in three stages:
- Improving the Current Implementation
- Enhancing with Hyperparameter Tuning and Other Methods
- Building a Character-Level CNN Using Only the URL Column
For each stage, I'll provide comprehensive code, explanations, and instructions on how to train, evaluate, save, and use the model for future predictions.
1. Improve Your Current Implementation
Improvements Overview:
- Early Stopping and Model Checkpointing: Prevent overfitting and save the best model based on validation loss.
- Enhanced Evaluation: Add more evaluation metrics and visualize training history.
- Data Cleaning: Ensure robust handling of missing values.
- Batch Normalization: Improve training stability and performance.
Complete Improved Code:
# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
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)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# Fix random seed for reproducibility
np.random.seed(42)
import tensorflow as tf
tf.random.set_seed(42)
# Read data
data = pd.read_csv('dataset_phishing.csv')
# Define features and target
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'] # Assuming 'status' is 1 for phishing and 0 for legitimate
# Handle missing values by replacing with median (more robust than filling with 0)
X.fillna(X.median(), inplace=True)
# Feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled = X_scaled.astype(float) # Ensure data type is float
# Reshape for Conv1D: (samples, timesteps, features)
X_reshaped = np.expand_dims(X_scaled, axis=2)
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
y_encoded = y_encoded.astype(float)
# Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_reshaped, y_encoded, test_size=0.2, random_state=42, stratify=y_encoded
)
# Define CNN model with improvements
model = Sequential()
# First Conv1D layer
model.add(Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=(X_reshaped.shape[1], 1)))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Second Conv1D layer
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Third Conv1D layer
model.add(Conv1D(filters=128, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Flatten and Dense layers
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid')) # Binary classification
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Summary of the model
model.summary()
# Define callbacks
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
checkpoint_path = 'best_model_improved.h5'
model_checkpoint = ModelCheckpoint(checkpoint_path, monitor='val_loss', save_best_only=True, verbose=1)
# Train the model
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop, model_checkpoint],
verbose=1
)
# Load the best model
model.load_weights(checkpoint_path)
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Test Loss: {loss:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
# Calculate additional metrics
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_prob)
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"ROC AUC: {roc_auc:.4f}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6,4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Legitimate', 'Phishing'], yticklabels=['Legitimate', 'Phishing'])
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title('Confusion Matrix')
plt.show()
# Plot training history
plt.figure(figsize=(12,5))
# Plot loss
plt.subplot(1,2,1)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.title('Loss over Epochs')
# Plot accuracy
plt.subplot(1,2,2)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.title('Accuracy over Epochs')
plt.show()
# Save the scaler and label encoder for future use
import joblib
scaler_path = 'scaler_improved.save'
encoder_path = 'label_encoder_improved.save'
joblib.dump(scaler, scaler_path)
joblib.dump(label_encoder, encoder_path)
print(f"Scaler saved to {scaler_path}")
print(f"Label Encoder saved to {encoder_path}")
# Instructions for Future Predictions
print("\nTo predict future data:")
print("1. Load the saved scaler and label encoder using joblib.")
print("2. Preprocess the new data in the same way as training data.")
print("3. Load the saved model and use model.predict() on the preprocessed data.")
Explanation and Steps for Future Predictions:
-
Training Improvements:
- Early Stopping: Stops training when validation loss doesn't improve for 10 epochs, preventing overfitting.
- Model Checkpoint: Saves the model with the best validation loss during training.
- Batch Normalization: Normalizes outputs of previous layers to stabilize and accelerate training.
- Enhanced Evaluation: Includes additional metrics and visualizations for a comprehensive evaluation.
-
Saving Artifacts:
- Model: The best model is saved as
best_model_improved.h5.
- Scaler and Label Encoder: Saved using
joblib for consistent preprocessing in future predictions.
-
Future Predictions Instructions:
- Load Saved Artifacts:
import joblib
from tensorflow.keras.models import load_model
# Load scaler and label encoder
scaler = joblib.load('scaler_improved.save')
label_encoder = joblib.load('label_encoder_improved.save')
# Load the saved model
model = load_model('best_model_improved.h5')
# Preprocess new data
new_data = pd.read_csv('new_data.csv') # Replace with your data
X_new = new_data[features]
X_new.fillna(X_new.median(), inplace=True)
X_new_scaled = scaler.transform(X_new)
X_new_scaled = np.expand_dims(X_new_scaled, axis=2).astype(float)
# Predict
y_new_pred_prob = model.predict(X_new_scaled).ravel()
y_new_pred = (y_new_pred_prob >= 0.5).astype(int)
y_new = label_encoder.inverse_transform(y_new_pred)
# Save predictions
new_data['predicted_status'] = y_new
new_data.to_csv('predictions.csv', index=False)
print("Predictions saved to predictions.csv")
2. Improve Current Implementation by Using Hyperparameter Tuning and Other Methods
Enhancements Overview:
- Hyperparameter Tuning: Utilize Keras Tuner to find the optimal combination of hyperparameters.
- Additional Callbacks: Include
ReduceLROnPlateau to adjust learning rate.
- Cross-Validation (Optional): Although computationally intensive, ensures model robustness.
Complete Enhanced Code with Hyperparameter Tuning:
# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
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)
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
# For hyperparameter tuning
import keras_tuner as kt
# Fix random seed for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Read data
data = pd.read_csv('dataset_phishing.csv')
# Define features and target
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'] # Assuming 'status' is 1 for phishing and 0 for legitimate
# Handle missing values by replacing with median
X.fillna(X.median(), inplace=True)
# Feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled = X_scaled.astype(float) # Ensure data type is float
# Reshape for Conv1D: (samples, timesteps, features)
X_reshaped = np.expand_dims(X_scaled, axis=2)
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
y_encoded = y_encoded.astype(float)
# Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_reshaped, y_encoded, test_size=0.2, random_state=42, stratify=y_encoded
)
# Define a model builder function for Keras Tuner
def model_builder(hp):
model = Sequential()
# Hyperparameter for number of Conv1D layers
for i in range(hp.Int('num_conv_layers', 1, 3)):
# Hyperparameter for number of filters
filters = hp.Choice(f'filters_{i}', values=[32, 64, 128])
# Hyperparameter for kernel size
kernel_size = hp.Choice(f'kernel_size_{i}', values=[3,5,7])
model.add(Conv1D(filters=filters, kernel_size=kernel_size, activation='relu',
input_shape=(X_reshaped.shape[1], 1) if i == 0 else None))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
# Hyperparameter for dropout rate
dropout_rate = hp.Float(f'dropout_{i}', 0.2, 0.5, step=0.1)
model.add(Dropout(dropout_rate))
model.add(Flatten())
# Hyperparameter for number of Dense layers
for j in range(hp.Int('num_dense_layers', 1, 2)):
units = hp.Int(f'units_{j}', min_value=64, max_value=256, step=64)
model.add(Dense(units, activation='relu'))
# Hyperparameter for dropout after dense layers
dropout_rate_dense = hp.Float(f'dropout_dense_{j}', 0.3, 0.6, step=0.1)
model.add(Dropout(dropout_rate_dense))
model.add(Dense(1, activation='sigmoid'))
# Hyperparameter for learning rate
learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='binary_crossentropy',
metrics=['accuracy']
)
return model
# Initialize the tuner
tuner = kt.RandomSearch(
model_builder,
objective='val_accuracy',
max_trials=20,
executions_per_trial=2,
directory='keras_tuner_dir',
project_name='phishing_detection_tuning'
)
# Display search space summary
tuner.search_space_summary()
# Define callbacks
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
checkpoint_path = 'best_model_tuned.h5'
model_checkpoint = ModelCheckpoint(checkpoint_path, monitor='val_loss', save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1)
# Search for best hyperparameters
tuner.search(
X_train, y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop, model_checkpoint, reduce_lr],
verbose=1
)
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"\nBest Hyperparameters:")
for hp in best_hps.values:
print(f" - {hp}: {best_hps.get(hp)}")
# Build the best model
model = tuner.hypermodel.build(best_hps)
# Train the best model
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop, model_checkpoint, reduce_lr],
verbose=1
)
# Load the best model
model.load_weights(checkpoint_path)
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"\nTest Accuracy: {accuracy:.4f}")
print(f"Test Loss: {loss:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
# Calculate additional metrics
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_prob)
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"ROC AUC: {roc_auc:.4f}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6,4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Greens', xticklabels=['Legitimate', 'Phishing'], yticklabels=['Legitimate', 'Phishing'])
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title('Confusion Matrix')
plt.show()
# Plot training history
plt.figure(figsize=(12,5))
# Plot loss
plt.subplot(1,2,1)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.title('Loss over Epochs')
# Plot accuracy
plt.subplot(1,2,2)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.title('Accuracy over Epochs')
plt.show()
# Save the scaler and label encoder for future use
import joblib
scaler_path = 'scaler_tuned.save'
encoder_path = 'label_encoder_tuned.save'
joblib.dump(scaler, scaler_path)
joblib.dump(label_encoder, encoder_path)
print(f"Scaler saved to {scaler_path}")
print(f"Label Encoder saved to {encoder_path}")
# Save the final model
model.save('best_model_tuned_final.h5')
print("Final tuned model saved as best_model_tuned_final.h5")
# Instructions for Future Predictions
print("\nTo predict future data:")
print("1. Load the saved scaler and label encoder using joblib.")
print("2. Preprocess the new data in the same way as training data.")
print("3. Load the saved model and use model.predict() on the preprocessed data.")
Explanation and Steps for Future Predictions:
-
Hyperparameter Tuning with Keras Tuner:
- Model Builder Function: Defines a flexible model where the number of Conv1D layers, filters, kernel sizes, dense layers, units, dropout rates, and learning rates are all hyperparameters to be tuned.
- Tuner Initialization: Uses
RandomSearch to explore the hyperparameter space efficiently.
- Search Execution: Searches for the best hyperparameters over 20 trials, each with 2 executions to average results.
-
Training the Best Model:
- After identifying the best hyperparameters, the model is rebuilt and trained with early stopping, model checkpointing, and learning rate reduction callbacks.
- The best model is saved as
best_model_tuned_final.h5.
-
Saving Artifacts:
- Scaler and Label Encoder: Saved using
joblib as scaler_tuned.save and label_encoder_tuned.save.
- Model: Saved as
best_model_tuned_final.h5.
-
Future Predictions Instructions:
- Load Saved Artifacts:
import joblib
from tensorflow.keras.models import load_model
# Load scaler and label encoder
scaler = joblib.load('scaler_tuned.save')
label_encoder = joblib.load('label_encoder_tuned.save')
# Load the saved model
model = load_model('best_model_tuned_final.h5')
# Preprocess new data
new_data = pd.read_csv('new_data.csv') # Replace with your data
X_new = new_data[features]
X_new.fillna(X_new.median(), inplace=True)
X_new_scaled = scaler.transform(X_new)
X_new_scaled = np.expand_dims(X_new_scaled, axis=2).astype(float)
# Predict
y_new_pred_prob = model.predict(X_new_scaled).ravel()
y_new_pred = (y_new_pred_prob >= 0.5).astype(int)
y_new = label_encoder.inverse_transform(y_new_pred)
# Save predictions
new_data['predicted_status'] = y_new
new_data.to_csv('predictions_tuned.csv', index=False)
print("Predictions saved to predictions_tuned.csv")
-
Notes:
- Keras Tuner Directory: The tuner saves its search logs in the
keras_tuner_dir/phishing_detection_tuning directory.
- Computational Resources: Hyperparameter tuning can be time-consuming. Ensure you have adequate computational resources or consider reducing
max_trials for quicker experimentation.
3. Use Character-Level CNN: Only Use URL Column to Do CNN Based on the URL
Overview:
Building a character-level CNN involves treating each URL as a sequence of characters. The steps include:
-
Data Preprocessing:
- Extract the URL column.
- Encode each character.
- Pad sequences to a fixed length.
-
Model Building:
- Use embedding layers or one-hot encoding.
- Employ Conv1D layers suitable for text classification.
-
Training, Evaluation, and Saving the Model:
- Similar to previous implementations with appropriate callbacks.
- Save the model and necessary preprocessing artifacts.
Complete Character-Level CNN Code:
# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import string
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, classification_report, confusion_matrix)
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, Embedding
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
# Fix random seed for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Read data
data = pd.read_csv('dataset_phishing.csv')
# Define URL and target
url_column = 'url'
target_column = 'status' # Assuming 'status' is 1 for phishing and 0 for legitimate
urls = data[url_column].astype(str)
y = data[target_column]
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
y_encoded = y_encoded.astype(float)
# Define maximum number of words (characters) and padding length
max_vocab = 100 # Number of unique characters
max_length = 100 # Maximum length of URLs; adjust as needed
# Create a list of unique characters
all_chars = ''.join(urls)
unique_chars = sorted(list(set(all_chars)))
print(f"Unique characters ({len(unique_chars)}): {unique_chars}")
# Initialize Tokenizer for character-level
tokenizer = Tokenizer(char_level=True, lower=True)
tokenizer.fit_on_texts(urls)
sequences = tokenizer.texts_to_sequences(urls)
# Vocabulary size (+1 for padding token)
vocab_size = len(tokenizer.word_index) + 1
print(f"Vocabulary Size: {vocab_size}")
# Pad sequences
X_padded = pad_sequences(sequences, maxlen=max_length, padding='post', truncating='post')
# Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_padded, y_encoded, test_size=0.2, random_state=42, stratify=y_encoded
)
# Define model parameters (can be tuned further)
embedding_dim = 64
# Define Character-Level CNN model
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
model.add(Conv1D(filters=128, kernel_size=3, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
model.add(Conv1D(filters=256, kernel_size=3, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid')) # Binary classification
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Summary of the model
model.summary()
# Define callbacks
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
checkpoint_path = 'best_model_char_cnn.h5'
model_checkpoint = ModelCheckpoint(checkpoint_path, monitor='val_loss', save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1)
# Train the model
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=64,
validation_split=0.2,
callbacks=[early_stop, model_checkpoint, reduce_lr],
verbose=1
)
# Load the best model
model.load_weights(checkpoint_path)
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Test Loss: {loss:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
# Calculate additional metrics
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_prob)
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"ROC AUC: {roc_auc:.4f}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6,4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Oranges', xticklabels=['Legitimate', 'Phishing'], yticklabels=['Legitimate', 'Phishing'])
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title('Confusion Matrix - Character-Level CNN')
plt.show()
# Plot training history
plt.figure(figsize=(12,5))
# Plot loss
plt.subplot(1,2,1)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.title('Loss over Epochs')
# Plot accuracy
plt.subplot(1,2,2)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.title('Accuracy over Epochs')
plt.show()
# Save the tokenizer and model for future use
import joblib
tokenizer_path = 'tokenizer_char_cnn.save'
joblib.dump(tokenizer, tokenizer_path)
print(f"Tokenizer saved to {tokenizer_path}")
# Save the model
model.save('best_model_char_cnn_final.h5')
print("Model saved as best_model_char_cnn_final.h5")
# Instructions for Future Predictions
print("\nTo predict future data:")
print("1. Load the saved tokenizer and label encoder using joblib.")
print("2. Preprocess the new URLs using the tokenizer and pad the sequences.")
print("3. Load the saved model and use model.predict() on the preprocessed URLs.")
# Example of Future Prediction
def predict_new_urls(new_urls, tokenizer, model, max_length=100):
sequences = tokenizer.texts_to_sequences(new_urls)
X_new = pad_sequences(sequences, maxlen=max_length, padding='post', truncating='post')
y_pred_prob = model.predict(X_new).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
return y_pred, y_pred_prob
# Example Usage:
# new_urls = ['http://example.com', 'http://phishing-site.com']
# y_pred, y_pred_prob = predict_new_urls(new_urls, tokenizer, model)
# print(y_pred, y_pred_prob)
Explanation and Steps for Future Predictions:
-
Data Preprocessing:
- Tokenizer:
- Character-Level Tokenizer:
char_level=True ensures each character is treated as a token.
- Vocabulary Size: Determined by the number of unique characters in the URLs.
- Sequence Padding:
- All URL sequences are padded to a fixed length (
max_length=100). Adjust this based on your dataset's URL lengths.
-
Model Architecture:
- Embedding Layer: Converts each character index to a dense vector of fixed size (
embedding_dim=64).
- Conv1D Layers: Capture local patterns in the character sequences.
- MaxPooling & Dropout: Reduce dimensionality and prevent overfitting.
- Fully Connected Layers: Aggregate features for final classification.
-
Saving Artifacts:
- Tokenizer: Saved as
tokenizer_char_cnn.save using joblib.
- Model: Saved as
best_model_char_cnn_final.h5.
-
Future Predictions Instructions:
- Load Saved Artifacts:
import joblib
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Load tokenizer and label encoder if necessary
tokenizer = joblib.load('tokenizer_char_cnn.save')
# Load the saved model
model = load_model('best_model_char_cnn_final.h5')
# Define a prediction function
def predict_new_urls(new_urls, tokenizer, model, max_length=100):
sequences = tokenizer.texts_to_sequences(new_urls)
X_new = pad_sequences(sequences, maxlen=max_length, padding='post', truncating='post')
y_pred_prob = model.predict(X_new).ravel()
y_pred = (y_pred_prob >= 0.5).astype(int)
return y_pred, y_pred_prob
# Example usage
new_urls = ['http://example.com', 'http://phishing-site.com']
y_pred, y_pred_prob = predict_new_urls(new_urls, tokenizer, model)
print("Predictions:", y_pred)
print("Prediction Probabilities:", y_pred_prob)
-
Notes:
- Character Coverage: Ensure that all characters in new URLs are present in the tokenizer's vocabulary. If there are new or unseen characters, you may need to handle them (e.g., by ignoring or mapping to a special token).
Conclusion
You've now enhanced your phishing detection system in three significant ways:
- Improved Current Implementation: Enhanced model architecture, better data handling, and comprehensive evaluation.
- Hyperparameter Tuning: Utilized Keras Tuner to fine-tune model parameters for optimal performance.
- Character-Level CNN: Developed a model that leverages the URL structure directly for prediction.
For each implementation, models are saved alongside necessary preprocessing artifacts, and detailed instructions are provided to facilitate future predictions seamlessly. Remember to validate models on diverse datasets to ensure their robustness and generalizability.
Feel free to reach out if you have further questions or need additional assistance!