Help me adjust my CNN implementation to use the new data splitting:
My implemntation:
import tensorflow as tf
import keras_tuner as kt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import EarlyStopping
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
print(f"""
The hyperparameter search is complete. The optimal number of filters in the first Conv1D layer is {best_hps.get('filters')} and the optimal learning rate for the optimizer is {best_hps.get('learning_rate')}.
""")
Build the model with the optimal hyperparameters and train it
model = tuner.hypermodel.build(best_hps)
history = model.fit(X_train, y_train, epochs=20, validation_split=0.2, callbacks=[stop_early])
Certainly! To adjust your Convolutional Neural Network (CNN) implementation to use the new data splitting strategy (70% training, 15% validation, and 15% test), you need to:
Update the Data Splitting Process: Implement the two-step splitting as you've outlined.
Modify the Model Training Process: Ensure that Keras Tuner uses the separate validation set instead of splitting the training data internally.
Adjust the Model Building Function if Necessary: Verify that the input shapes and other parameters align with the new data shapes.
Below is the revised implementation with detailed explanations for each change:
python
import tensorflow as tf
import keras_tuner as kt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import EarlyStopping
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
# Set seeds for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Read data
data = pd.read_csv('dataset_phishing.csv')
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']
# Check for any missing values and handle them if necessary
X.fillna(0, inplace=True)
# Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Reshape data for Conv1D (samples, timesteps, features)
# Since Conv1D expects a 3D input, we'll treat each feature as a timestep with 1 feature
# Alternatively, you can treat it as a single timestep with multiple features
# Here, we'll use the first approach
X_reshaped = np.expand_dims(X_scaled, axis=2) # Shape: (samples, features, 1)
# Encode labels to binary values (0/1)
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# New Data Splitting Strategy
# Step 1: Split data into 70% train and 30% temp (validation + test)
X_train, X_temp, y_train, y_temp = train_test_split(
X_reshaped, 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
)
print(f"Training set shape: {X_train.shape}, {y_train.shape}")
print(f"Validation set shape: {X_val.shape}, {y_val.shape}")
print(f"Test set shape: {X_test.shape}, {y_test.shape}")
def model_builder(hp):
model = Sequential()
# First Conv1D Layer
model.add(Conv1D(
filters=hp.Int('filters', min_value=32, max_value=128, step=32),
kernel_size=hp.Choice('kernel_size', values=[3, 5]),
activation='relu',
input_shape=(X_reshaped.shape[1], 1), # Adjusted for Conv1D input
kernel_regularizer=l2(0.0001)
))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(hp.Float('dropout_rate', min_value=0.1, max_value=0.5, step=0.1)))
# Second Conv1D Layer
model.add(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',
kernel_regularizer=l2(0.0001)
))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(hp.Float('dropout_rate_2', min_value=0.1, max_value=0.5, step=0.1)))
model.add(Flatten())
# Dense Layer
model.add(Dense(
units=hp.Int('units', min_value=64, max_value=256, step=64),
activation='relu'
))
model.add(Dropout(hp.Float('dropout_rate_3', min_value=0.1, max_value=0.5, step=0.1)))
# Output Layer
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(
optimizer=Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])),
loss='binary_crossentropy',
metrics=['accuracy']
)
return model
# Initialize Keras Tuner with Hyperband
tuner = kt.Hyperband(
model_builder,
objective='val_accuracy',
max_epochs=20,
factor=3,
directory='my_dir',
project_name='phishing_tuning'
)
# Early Stopping Callback
stop_early = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
# Perform Hyperparameter Search using the training and validation sets
tuner.search(
X_train, y_train,
epochs=50,
validation_data=(X_val, y_val),
callbacks=[stop_early]
)
# Retrieve the best hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete.
Optimal number of filters in the first Conv1D layer: {best_hps.get('filters')}.
Optimal learning rate for the optimizer: {best_hps.get('learning_rate')}.
""")
# Build the model with the optimal hyperparameters and train it on the combined training and validation sets
# This ensures the model benefits from all available training data
model = tuner.hypermodel.build(best_hps)
# Combine training and validation data for final training
X_combined = np.concatenate((X_train, X_val), axis=0)
y_combined = np.concatenate((y_train, y_val), axis=0)
# Train the model
history = model.fit(
X_combined, y_combined,
epochs=20,
validation_split=0.0, # No validation split since we have a separate test set
callbacks=[stop_early]
)
# Evaluate the model on the test set
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")
# Predict the labels for X_test
y_pred = model.predict(X_test)
# Convert probabilities to binary output (0 or 1)
y_pred_binary = (y_pred > 0.5).astype(int)
# Get classification report with more decimal places
print(classification_report(y_test, y_pred_binary, digits=4))
# Plot learning curve
plt.figure(figsize=(12, 6))
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy') # If validation_accuracy exists
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Learning Curve')
plt.legend()
plt.show()
Conv1D expects a 3D input. Here, each feature is treated as a timestep with a single feature. Adjust axis as needed based on your data interpretation.
Updating the Keras Tuner Search:
Using Separate Validation Data:
Instead of using validation_split within tuner.search, provide the validation data directly. This avoids overlapping splits and ensures that the validation set remains consistent.
Combining Training and Validation Sets for Final Training:
After hyperparameter tuning, it's common to retrain the model on the combined training and validation sets to utilize all available data before evaluating on the test set.
python
Summary of the Revised Workflow
Data Preparation:
Load and preprocess the data (handle missing values, scale features, encode labels).
Reshape the data to fit Conv1D requirements.
Data Splitting:
Split data into 70% training, 15% validation, and 15% test sets using stratified splits.
Model Building and Hyperparameter Tuning:
Define a model_builder function for Keras Tuner.
Initialize the tuner with Hyperband and perform the search using the training and validation sets.
Final Model Training:
After finding the best hyperparameters, combine the training and validation sets.
Train the final model on the combined set.
Evaluation:
Evaluate the final model on the test set.
Generate and display classification metrics.
Plot the learning curve.
By following the revised implementation above, your CNN model will utilize the new data splitting strategy effectively, ensuring a more robust evaluation of its performance on unseen data.
X_combined = np.concatenate((X_train, X_val), axis=0)
y_combined = np.concatenate((y_train, y_val), axis=0)
history = model.fit(
X_combined, y_combined,
epochs=20,
validation_split=0.0, # No validation split since we have a separate test set
callbacks=[stop_early]
)
Adjusting the Learning Curve Plot:
Since the final training includes the validation set as training data, the validation curve may not be as meaningful. However, if you wish to see the performance during training, you can keep it. Alternatively, you can omit validation metrics.
Stratified Splitting: Using stratify in train_test_split helps maintain the class distribution across training, validation, and test sets, which is crucial for classification tasks, especially if the classes are imbalanced.
Restoring Best Weights: In the EarlyStopping callback, setting restore_best_weights=True ensures that the model retains the weights from the epoch with the best validation loss.
Hyperparameter Tuning Trials: Depending on computational resources, consider adjusting max_epochs and factor in the Hyperband tuner to balance between search breadth and computational feasibility.
Monitoring Additional Metrics: Besides accuracy, you may want to monitor other metrics like Precision, Recall, or AUC, especially if dealing with imbalanced datasets.