Sure! Below are the implementations for each of your requests, including code, explanations, saving the best model, and instructions on how to predict future data using the trained models.
1. Improve Your Current Implementation
To improve your current CNN implementation for phishing detection, we'll:
- Enhance Data Preprocessing: Handle class imbalance with SMOTE and ensure proper data scaling.
- Improve Model Architecture: Adjust layers and hyperparameters for better performance.
- Implement Callbacks: Use
EarlyStopping and ModelCheckpoint to prevent overfitting and save the best model.
- Include Evaluation Metrics: Evaluate the model using precision, recall, F1-score, and confusion matrix.
Improved Code:
# Import necessary packages
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix
from imblearn.over_sampling import SMOTE # Install using `pip install imblearn`
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# 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'] # 'status' column: 1 for phishing, 0 for legitimate
# Handle missing values
X.fillna(0, inplace=True)
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# Handle class imbalance using SMOTE
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X, y_encoded)
# Scale features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_resampled)
# Reshape data for Conv1D
X_reshaped = np.expand_dims(X_scaled, axis=2)
# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_reshaped, y_resampled, test_size=0.2, random_state=42)
# Define CNN model with improved architecture
model = Sequential([
Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(X_reshaped.shape[1], 1)),
MaxPooling1D(pool_size=2),
Dropout(0.3),
Conv1D(filters=128, kernel_size=3, activation='relu'),
MaxPooling1D(pool_size=2),
Dropout(0.3),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.4),
Dense(1, activation='sigmoid') # Binary classification
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Define callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1)
model_checkpoint = ModelCheckpoint('best_model_improved.h5', monitor='val_accuracy',
save_best_only=True, verbose=1)
# Train the model
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=64,
validation_data=(X_test, y_test),
callbacks=[early_stopping, model_checkpoint]
)
# Load the best saved model weights
model.load_weights('best_model_improved.h5')
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test)
y_pred = (y_pred_prob > 0.5).astype(int).flatten()
# Classification report
print(classification_report(y_test, y_pred))
# Confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
Explanation:
- Data Preprocessing Enhancements:
- SMOTE: We used SMOTE to handle class imbalance by oversampling the minority class.
- Scaling: Applied
StandardScaler to standardize features.
- Model Improvements:
- Increased the number of filters and added an additional Conv1D layer for better feature extraction.
- Adjusted dropout rates to prevent overfitting.
- Callbacks:
- EarlyStopping: Stops training when validation loss doesn't improve for 5 epochs.
- ModelCheckpoint: Saves the best model based on validation accuracy during training.
- Evaluation Metrics:
- Used
classification_report and confusion_matrix to evaluate precision, recall, F1-score, and confusion matrix.
Predicting Future Data Using the Trained Model:
# Load new data
new_data = pd.read_csv('new_dataset_phishing.csv') # Replace with your new data file
X_new = new_data[features]
# Handle missing values
X_new.fillna(0, inplace=True)
# Scale features using the previously fitted scaler
X_new_scaled = scaler.transform(X_new)
# Reshape data
X_new_reshaped = np.expand_dims(X_new_scaled, axis=2)
# Load the best saved model
model.load_weights('best_model_improved.h5')
# Predict
y_new_pred_prob = model.predict(X_new_reshaped)
y_new_pred = (y_new_pred_prob > 0.5).astype(int).flatten()
# Decode labels if needed
y_new_labels = label_encoder.inverse_transform(y_new_pred)
# Add predictions to new data
new_data['Predicted Status'] = y_new_labels
# Save predictions
new_data.to_csv('new_phishing_predictions.csv', index=False)
2. Improve Implementation with Hyperparameter Tuning
We'll enhance the model by tuning hyperparameters using Keras Tuner. This helps find the best combination of parameters for optimal performance.
Code with Hyperparameter Tuning:
First, install Keras Tuner:
pip install keras-tuner
# Import necessary packages
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix
from imblearn.over_sampling import SMOTE
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import keras_tuner as kt
# [Data preprocessing same as in the previous implementation]
# Define model-building function for Keras Tuner
def build_model(hp):
model = models.Sequential()
model.add(layers.Conv1D(
filters=hp.Int('filters_1', min_value=32, max_value=128, step=32),
kernel_size=hp.Choice('kernel_size_1', values=[3, 5]),
activation='relu',
input_shape=(X_reshaped.shape[1], 1)
))
model.add(layers.MaxPooling1D(pool_size=2))
model.add(layers.Dropout(hp.Float('dropout_1', min_value=0.2, max_value=0.5, step=0.1)))
model.add(layers.Conv1D(
filters=hp.Int('filters_2', min_value=64, max_value=256, step=64),
kernel_size=hp.Choice('kernel_size_2', values=[3, 5]),
activation='relu'
))
model.add(layers.MaxPooling1D(pool_size=2))
model.add(layers.Dropout(hp.Float('dropout_2', min_value=0.2, max_value=0.5, step=0.1)))
model.add(layers.Flatten())
model.add(layers.Dense(
units=hp.Int('units', min_value=64, max_value=256, step=64),
activation='relu'
))
model.add(layers.Dropout(hp.Float('dropout_dense', min_value=0.2, max_value=0.5, step=0.1)))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(
optimizer=hp.Choice('optimizer', values=['adam', 'rmsprop']),
loss='binary_crossentropy',
metrics=['accuracy']
)
return model
# Initialize Keras Tuner
tuner = kt.RandomSearch(
build_model,
objective='val_accuracy',
max_trials=10,
directory='tuner_dir',
project_name='phishing_detection_tuning')
# Define early stopping callback
early_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1)
# Run hyperparameter search
tuner.search(X_train, y_train,
epochs=10,
batch_size=64,
validation_data=(X_test, y_test),
callbacks=[early_stopping])
# Get the best hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
# Build model with the best hyperparameters
model = tuner.hypermodel.build(best_hps)
# Define checkpoint callback
model_checkpoint = ModelCheckpoint('best_model_tuned.h5', monitor='val_accuracy',
save_best_only=True, verbose=1)
# Train the model with early stopping and model checkpoint
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=64,
validation_data=(X_test, y_test),
callbacks=[early_stopping, model_checkpoint]
)
# Load the best saved model
model.load_weights('best_model_tuned.h5')
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test)
y_pred = (y_pred_prob > 0.5).astype(int).flatten()
# Classification report
print(classification_report(y_test, y_pred))
# Confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
Explanation:
- Hyperparameter Tuning:
- Defined a model-building function
build_model with tunable hyperparameters.
- Used
RandomSearch from Keras Tuner to search for the best hyperparameters.
- Hyperparameters Tuned:
- Number of filters in Conv1D layers.
- Kernel sizes.
- Dropout rates.
- Units in the dense layer.
- Optimizer choice.
- Training with Best Hyperparameters:
- Built and trained the model with the best hyperparameters found.
- Used
EarlyStopping and ModelCheckpoint callbacks.
- Evaluation:
- Loaded the best model and evaluated it using the test data.
Predicting Future Data Using the Trained Model:
Same as before, but load best_model_tuned.h5:
# Load the best saved model
model.load_weights('best_model_tuned.h5')
# Predict on new data
# [Use the same preprocessing and prediction steps as before]
3. Use Character-Level CNN with URL Column
We'll build a character-level CNN that processes URLs directly. This involves:
- Tokenizing URLs at the character level.
- Converting characters to numerical sequences.
- Building a CNN model suitable for text data.
Code for Character-Level CNN:
# Import necessary packages
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, Conv1D, MaxPooling1D, GlobalMaxPooling1D, Dense, Dropout
# Read data
data = pd.read_csv('dataset_phishing.csv')
# Extract URLs and labels
X = data['url']
y = data['status'] # 'status' column: 1 for phishing, 0 for legitimate
# Encode labels
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# Tokenize URLs at character level
tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts(X)
# Convert URLs to sequences
sequences = tokenizer.texts_to_sequences(X)
# Determine maximum sequence length
max_seq_length = max(len(seq) for seq in sequences)
# Pad sequences
X_padded = pad_sequences(sequences, maxlen=max_seq_length, padding='post')
# Split data 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)
# Define model
vocab_size = len(tokenizer.word_index) + 1 # Add 1 for padding token
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=64, input_length=max_seq_length),
Conv1D(filters=64, kernel_size=5, activation='relu'),
MaxPooling1D(pool_size=2),
Dropout(0.3),
Conv1D(filters=128, kernel_size=5, activation='relu'),
MaxPooling1D(pool_size=2),
Dropout(0.3),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.4),
Dense(1, activation='sigmoid')
])
# Compile model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Define callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1)
model_checkpoint = ModelCheckpoint('best_char_cnn_model.h5', monitor='val_accuracy',
save_best_only=True, verbose=1)
# Train model
history = model.fit(
X_train, y_train,
epochs=30,
batch_size=128,
validation_data=(X_test, y_test),
callbacks=[early_stopping, model_checkpoint]
)
# Load the best saved model
model.load_weights('best_char_cnn_model.h5')
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")
# Predict on test data
y_pred_prob = model.predict(X_test)
y_pred = (y_pred_prob > 0.5).astype(int).flatten()
# Classification report
print(classification_report(y_test, y_pred))
# Confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
Explanation:
- Character-Level Tokenization:
- Tokenized URLs at the character level to capture character patterns.
- Sequence Conversion and Padding:
- Converted character tokens into sequences of integers.
- Padded sequences to have the same length.
- Model Architecture:
- Embedding Layer: Converts integer sequences into dense vectors.
- Conv1D Layers: Extract n-gram features from character sequences.
- Pooling Layers: Reduce dimensionality and capture important features.
- Flatten and Dense Layers: Classify the features into phishing or legitimate.
- Training and Callbacks:
- Used
EarlyStopping and ModelCheckpoint.
- Evaluation:
- Evaluated the model using accuracy, precision, recall, and confusion matrix.
Predicting Future Data Using the Trained Model:
# Load new data
new_data = pd.read_csv('new_url_data.csv') # Replace with your new data file
X_new = new_data['url']
# Tokenize URLs using the same tokenizer
sequences_new = tokenizer.texts_to_sequences(X_new)
# Pad sequences
X_new_padded = pad_sequences(sequences_new, maxlen=max_seq_length, padding='post')
# Load the best saved model
model.load_weights('best_char_cnn_model.h5')
# Predict
y_new_pred_prob = model.predict(X_new_padded)
y_new_pred = (y_new_pred_prob > 0.5).astype(int).flatten()
# Decode labels if needed
y_new_labels = label_encoder.inverse_transform(y_new_pred)
# Add predictions to new data
new_data['Predicted Status'] = y_new_labels
# Save predictions
new_data.to_csv('new_url_predictions.csv', index=False)
Summary and Next Steps
- Model Saving: In each implementation, the best model is saved during training with
ModelCheckpoint.
- Prediction on New Data: Follow the provided steps in each implementation to predict future data using the trained models.
- Customization: Feel free to adjust hyperparameters, layers, and other settings based on your dataset's characteristics.
- Evaluation: Always evaluate your models using multiple metrics to get a comprehensive understanding of their performance.
Note: Ensure that the necessary libraries (imblearn, keras-tuner, etc.) are installed in your environment before running the code.
If you have any questions or need further assistance with these implementations, feel free to ask!