Train Loss decreases steadily, but Val Loss increases from around epoch 25 and fluctuates at a high value.
Train Accuracy improves to around 0.8, while Val Accuracy remains low and unstable around 0.5, indicating overfitting after a certain point.
Leg Direction Loss and Accuracy:
code
Train Loss decreases smoothly and reaches a low level.
Val Loss is more variable, though it trends downwards.
Train Accuracy is high (~0.98), while Val Accuracy is low and fluctuates around 0.9, showing some generalization issues. Classification Report for 'percent_change_classification':
precision recall f1-score support
0 0.05 0.04 0.04 27
1 0.00 0.00 0.00 7
2 0.00 0.00 0.00 6
3 0.08 0.07 0.08 27
4 0.60 0.72 0.65 102
5 0.00 0.00 0.00 9
accuracy 0.43 178
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import logging
from ta.volatility import AverageTrueRange, BollingerBands
from ta.momentum import RSIIndicator
from ta.trend import MACD, ADXIndicator
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import (
Input,
Dense,
Dropout,
MultiHeadAttention,
LayerNormalization,
GlobalAveragePooling1D,
Add
)
from tensorflow.keras.models import Model
import tensorflow as tf
from binance.client import Client
df['BB_mavg'] = df['BB_width'].rolling(window=20).mean()
df['BB_vol'] = np.where(df['BB_width'] > 1.2 * df['BB_mavg'], 'High',
np.where(df['BB_width'] < 0.8 * df['BB_mavg'], 'Low', 'Medium'))
df['daily_return'] = df['close'].pct_change()
df['RV'] = df['daily_return'].rolling(window=20).std() * np.sqrt(252)
rv_80 = df['RV'].quantile(0.8)
rv_20 = df['RV'].quantile(0.2)
df['RV_vol'] = np.where(df['RV'] > rv_80, 'High',
np.where(df['RV'] < rv_20, 'Low', 'Medium'))
df['Volatility'] = df[['ATR_vol', 'BB_vol', 'RV_vol']].mode(axis=1)[0]
df['Trend'] = np.where(
(df['MACD'] > df['MACD_signal']) & (df['MACD'] > 0), 'Bullish',
np.where(
(df['MACD'] < df['MACD_signal']) & (df['MACD'] < 0), 'Bearish', 'Neutral'
)
)
df['Trend_strength'] = np.where(df['ADX'] > 25, 'Strong', 'Weak')
df['Market_Environment'] = df.apply(
lambda row: f"{row['Volatility']} Vol/{row['Trend']}" if row['Trend_strength'] == 'Strong' else f"{row['Volatility']} Vol/Neutral",
axis=1
)
# Encode categorical data to numeric
label_encoders = {}
for column in ['ATR_vol', 'BB_vol', 'RV_vol', 'Volatility', 'Trend', 'Trend_strength', 'Market_Environment']:
le = LabelEncoder()
df[column] = le.fit_transform(df[column].astype(str))
label_encoders[column] = le # Save encoder for each column if you need to decode later
return df, label_encoders # Returning encoders in case needed
def calculate_leg_data(df):
"""
Calculate leg data: current and previous leg percent change and length.
"""
df['percent_delta'] = df['close'].pct_change()
df = df.reset_index(drop=True)
percentiles = df['percent_change'].quantile([0.05, 0.20, 0.40, 0.60, 0.80, 0.95]).to_dict()
def classify(x, p):
if x < p[0.05]:
return 'Down a Lot'
elif x < p[0.20]:
return 'Down Moderate'
elif x < p[0.40]:
return 'Down a Little'
elif x < p[0.60]:
return 'No Change'
elif x < p[0.80]:
return 'Up a Little'
elif x < p[0.95]:
return 'Up Moderate'
else:
return 'Up a Lot'
df['percent_change_classification'] = df['percent_change'].apply(lambda x: classify(x, percentiles))
return df
def encode_and_scale(df, label_encoders=None, scalers=None):
"""
Encode categorical features and scale numerical features.
"""
if label_encoders is None:
label_encoders = {}
if scalers is None:
scalers = {}
code
# 1. Encode Categorical Input Features
categorical_features = ['percent_change_classification', 'Market_Environment']
for col in categorical_features:
le = LabelEncoder()
df[f'{col}_encoded'] = le.fit_transform(df[col].astype(str))
label_encoders[col] = le # Save the encoder for future use
# 2. Encode Categorical Target Features (if applicable)
# In this case, 'leg_direction' is binary (0 or 1), so no encoding is needed.
# 3. Scale Numerical Features
numerical_features = [
'RSI', 'MACD', 'MACD_signal', 'ATR', 'BB_width',
'previous_leg_change', 'previous_leg_length',
'current_leg_change', 'current_leg_length'
]
scaler = StandardScaler()
df[numerical_features] = scaler.fit_transform(df[numerical_features])
scalers['numerical'] = scaler # Save the scaler for future use
return df, label_encoders, scalers
def build_enhanced_transformer_model(
input_shape,
num_classes_classification,
head_size=16,
num_heads=4,
ff_dim=32,
num_transformer_blocks=2,
dropout=0.3,
l2_reg=1e-3
):
"""
Builds an enhanced Transformer model with multiple transformer blocks and positional encoding.
code
Args:
input_shape (tuple): Shape of the input data (seq_length, num_features).
num_classes_classification (int): Number of classes for percent_change_classification.
head_size (int): Size of each attention head.
num_heads (int): Number of attention heads.
ff_dim (int): Dimension of the feed-forward network.
num_transformer_blocks (int): Number of Transformer blocks.
dropout (float): Dropout rate.
l2_reg (float): L2 regularization factor.
Returns:
keras.Model: Compiled Keras model.
"""
seq_length, num_features = input_shape
inputs = Input(shape=input_shape, name='input')
# Feature Embedding
x = Dense(head_size * num_heads, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(l2_reg))(inputs)
# Add Positional Encoding
pe = positional_encoding(seq_length, head_size * num_heads)
x += tf.cast(pe, dtype=tf.float32)
# Transformer Blocks
for i in range(num_transformer_blocks):
# Layer Normalization
x_norm = LayerNormalization(epsilon=1e-6, name=f'layer_norm_{i}')(x)
# Multi-Head Self-Attention
attention = MultiHeadAttention(
key_dim=head_size,
num_heads=num_heads,
dropout=dropout,
name=f'mha_{i}'
)(x_norm, x_norm)
attention = Dropout(dropout)(attention)
x = Add(name=f'attention_residual_{i}')([x, attention]) # Residual connection
# Layer Normalization
x_norm = LayerNormalization(epsilon=1e-6, name=f'ffn_layer_norm_{i}')(x)
# Feed-Forward Network
ffn = Dense(ff_dim, activation='gelu',
kernel_regularizer=tf.keras.regularizers.l2(l2_reg))(x_norm)
ffn = Dropout(dropout)(ffn)
ffn = Dense(head_size * num_heads,
kernel_regularizer=tf.keras.regularizers.l2(l2_reg))(ffn)
ffn = Dropout(dropout)(ffn)
x = Add(name=f'ffn_residual_{i}')([x, ffn]) # Residual connection
# Global Pooling and Dense Layers
x = LayerNormalization(epsilon=1e-6)(x)
x = GlobalAveragePooling1D()(x)
x = Dropout(dropout)(x)
x = Dense(ff_dim, activation='gelu',
kernel_regularizer=tf.keras.regularizers.l2(l2_reg))(x)
x = Dropout(dropout)(x)
x = Dense(64, activation='gelu',
kernel_regularizer=tf.keras.regularizers.l2(l2_reg))(x)
x = Dropout(dropout)(x)
# Outputs
percent_change_output = Dense(
num_classes_classification,
activation='softmax',
name='percent_change_classification'
)(x)
leg_direction_output = Dense(
1,
activation='sigmoid',
name='leg_direction'
)(x)
# Define Model with Named Outputs
model = Model(
inputs=inputs,
outputs={
'percent_change_classification': percent_change_output,
'leg_direction': leg_direction_output
}
)
return model
def compile_enhanced_multi_output_model(model, learning_rate=1e-3):
"""
Compiles the enhanced multi-output Transformer model with appropriate loss functions and metrics.
code
Args:
model (keras.Model): The Keras model to compile.
learning_rate (float): Learning rate for the optimizer.
Returns:
keras.Model: The compiled Keras model.
"""
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss={
'percent_change_classification': 'sparse_categorical_crossentropy',
'leg_direction': 'binary_crossentropy'
},
metrics={
'percent_change_classification': ['accuracy'],
'leg_direction': ['accuracy']
}
)
return model
def main():
# Configuration
BINANCE_API_KEY = 'YOUR_API_KEY' # Replace with your API key
BINANCE_API_SECRET = 'YOUR_API_SECRET' # Replace with your API secret
code
SYMBOL = 'BTCUSDT' # You can change this to your desired symbol
INTERVAL = '1s' # Changed to '1m' for practicality; '1s' may cause rate limits
SEQ_LENGTH = 60 # Number of time steps in each input sequence
TARGET_STEPS = 1 # Predicting the next time step
LIMIT = 100000 # Increased to 5000 for better training
# Initialize Binance client
client = Client(BINANCE_API_KEY, BINANCE_API_SECRET)
# Load and prepare data
print("Loading data...")
df = load_data(client, SYMBOL, interval=INTERVAL, limit=LIMIT)
if df.empty:
print("No data fetched. Exiting.")
return
print("Adding technical indicators...")
df = add_technical_indicators(df)
print("Classifying market environments...")
df, market_env_encoders = classify_market_environments(df)
print("Calculating leg data...")
df = calculate_leg_data(df)
print("Classifying percent changes...")
df = classify_percent_change(df)
# Encode and scale data
print("Encoding and scaling data...")
df, label_encoders, scalers = encode_and_scale(df)
# Prepare sequences with two targets
print("Preparing sequences...")
X, Y = prepare_sequences(df, SEQ_LENGTH, TARGET_STEPS)
# Validate data shapes
print(f"Shape of X: {X.shape}")
for key in Y:
print(f"Shape of Y[{key}]: {Y[key].shape}")
# Check if data is sufficient
if len(X) == 0:
print("Insufficient data after preparing sequences.")
return
# Unpack Y dictionary
Y_percent_change = Y['percent_change_classification']
Y_leg_direction = Y['leg_direction']
# Assert consistent sample sizes
assert X.shape[0] == Y_percent_change.shape[0] == Y_leg_direction.shape[0], "Mismatch in sample sizes between X and Y."
# Verify label ranges
print("Verifying label ranges...")
print(f"percent_change_classification labels: min={Y_percent_change.min()}, max={Y_percent_change.max()}")
print(f"leg_direction labels: min={Y_leg_direction.min()}, max={Y_leg_direction.max()}")
assert Y_percent_change.min() >= 0 and Y_percent_change.max() < 7, "percent_change_classification labels out of range [0,6]"
assert Y_leg_direction.min() >= 0 and Y_leg_direction.max() <= 1, "leg_direction labels should be binary (0 or 1)"
# Address Class Imbalance
from collections import Counter
counter = Counter(Y_percent_change)
print("Class distribution for 'percent_change_classification':", counter)
# Calculate class weights
total = sum(counter.values())
class_weights = {cls: total / (len(counter) * count) for cls, count in counter.items()}
print("Class Weights:", class_weights)
# Split data
print("Splitting data into training and testing sets...")
X_train, X_test, y_percent_change_train, y_percent_change_test, y_leg_direction_train, y_leg_direction_test = train_test_split(
X,
Y_percent_change,
Y_leg_direction,
test_size=0.2,
random_state=42,
stratify=Y_percent_change # Ensure stratified split for classification
)
# Reassemble Y_train and Y_test dictionaries
Y_train = {
'percent_change_classification': y_percent_change_train,
'leg_direction': y_leg_direction_train
}
Y_test = {
'percent_change_classification': y_percent_change_test,
'leg_direction': y_leg_direction_test
}
# Check unique labels and sample labels
print("Unique labels for 'percent_change_classification':", np.unique(Y_train['percent_change_classification']))
print("Sample labels:", Y_train['percent_change_classification'][:10])
print("Unique labels for 'leg_direction':", np.unique(Y_train['leg_direction']))
print("Sample labels:", Y_train['leg_direction'][:10])
# Build and compile model
print("Building the Enhanced Transformer model...")
input_shape = (SEQ_LENGTH, X.shape[2]) # (60, num_features)
num_classes = len(np.unique(Y_percent_change)) # Should be 7
model = build_enhanced_transformer_model(
input_shape=input_shape,
num_classes_classification=num_classes,
head_size=64,
num_heads=4,
ff_dim=128,
num_transformer_blocks=4,
dropout=0.1,
l2_reg=1e-4
)
model = compile_enhanced_multi_output_model(model, learning_rate=1e-3)
# Print model summary
print("Model Summary:")
model.summary()
# Implement Early Stopping and Learning Rate Scheduler
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor='val_percent_change_classification_accuracy',
patience=10,
restore_best_weights=True
)
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(
monitor='val_percent_change_classification_accuracy',
factor=0.5,
patience=5,
verbose=1
)
# Train model
print("Training the model...")
history = model.fit(
X_train,
{
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction']
},
epochs=200,
batch_size=32,
validation_split=0.2
)
# Save encoders and scalers for future use
print("Saving label encoders and scalers...")
with open('label_encoders.pkl', 'wb') as f:
pickle.dump(label_encoders, f)
with open('scalers.pkl', 'wb') as f:
pickle.dump(scalers, f)
# Save the model
print("Saving the trained model...")
model.save('enhanced_multi_output_transformer_model.h5')
# Evaluate the model
print("Evaluating the model on test data...")
eval_results = model.evaluate(
X_test,
Y_test,
verbose=0
)
for name, value in zip(model.metrics_names, eval_results):
print(f"{name}: {value:.4f}")
# Generate classification reports
from sklearn.metrics import classification_report, confusion_matrix
# Predict on test data
predictions = model.predict(X_test)
predicted_classes = np.argmax(predictions['percent_change_classification'], axis=1)
print("Classification Report for 'percent_change_classification':")
print(classification_report(Y_test['percent_change_classification'], predicted_classes))
# Confusion Matrix
cm = confusion_matrix(Y_test['percent_change_classification'], predicted_classes)
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix for Percent Change Classification')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.savefig("confusion_matrix.png")
plt.close()
# Visualize training history
print("Plotting training history...")
plt.figure(figsize=(12, 8))
# Plot Loss
plt.subplot(2, 2, 1)
plt.plot(history.history['percent_change_classification_loss'], label='Train Loss')
plt.plot(history.history['val_percent_change_classification_loss'], label='Val Loss')
plt.title('Percent Change Classification Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Plot Accuracy
plt.subplot(2, 2, 2)
plt.plot(history.history['percent_change_classification_accuracy'], label='Train Accuracy')
plt.plot(history.history['val_percent_change_classification_accuracy'], label='Val Accuracy')
plt.title('Percent Change Classification Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# Loss for Leg Direction
plt.subplot(2, 2, 3)
plt.plot(history.history['leg_direction_loss'], label='Train Loss')
plt.plot(history.history['val_leg_direction_loss'], label='Val Loss')
plt.title('Leg Direction Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Accuracy for Leg Direction
plt.subplot(2, 2, 4)
plt.plot(history.history['leg_direction_accuracy'], label='Train Accuracy')
plt.plot(history.history['val_leg_direction_accuracy'], label='Val Accuracy')
plt.title('Leg Direction Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.savefig("training_history_enhanced.png")
plt.close()
print("Training complete. Plots saved.")
return model, history
if name == "main":
model, history = main()
Based on the provided training observations and the accompanying code, it's clear that your multi-output Transformer model is encountering significant challenges, particularly with the percent_change_classification task. Let's delve into a comprehensive analysis of the issues and outline actionable strategies to enhance your model's performance.
1. Understanding the Current Model Performance
a. percent_change_classification
Training Behavior:
Train Loss: Decreases steadily.
Validation Loss: Increases from around epoch 25 and fluctuates at a high value.
Train Accuracy: Improves to around 0.8.
Validation Accuracy: Remains low and unstable around 0.5.
Classification Report:
Class 4: Reasonably performing with precision=0.60, recall=0.72, f1-score=0.65.
Other Classes (0,1,2,3,5): Poor performance with near-zero metrics.
Interpretation: The model is overfitting to the training data, especially to the majority class (Class 4). The poor performance on minority classes indicates class imbalance issues.
b. leg_direction
Training Behavior:
Train Loss: Decreases smoothly and reaches a low level.
Validation Loss: More variable but trends downward.
Train Accuracy: High (~0.98).
Validation Accuracy: Low and fluctuates around 0.9.
Interpretation: While the model shows high training accuracy, the validation accuracy suggests some degree of overfitting. However, the performance is comparatively better than the classification task.
2. Identifying Root Causes
a. Class Imbalance
The percent_change_classification problem appears to be highly imbalanced. From your classification report, it's evident that one class dominates (Class 4), while others have negligible representation. This imbalance can mislead the model to prioritize the majority class, resulting in poor generalization to minority classes.
b. Model Complexity and Overfitting
Your Transformer-based architecture is quite sophisticated. While powerful, such models are prone to overfitting, especially when dealing with imbalanced datasets and limited data.
c. Lack of Class Weighting in Training
Although you've calculated class weights in your code, they aren't being utilized during the training process. Proper class weighting can help the model pay more attention to minority classes.
d. Evaluation Metrics
Relying solely on accuracy isn't effective for imbalanced datasets. Metrics like precision, recall, and F1-score provide a more nuanced view of model performance across different classes.
3. Recommended Solutions
a. Addressing Class Imbalance
Implement Class Weighting:
You've already calculated class weights. Integrate them into the model.fit method to penalize misclassification of minority classes more heavily.
python
# Inside your main() function, before model.fit()
# Prepare class weights for 'percent_change_classification'
class_weights_percent_change = class_weights # From your existing calculation
# Assemble class weights for multi-output
class_weight_dict = {
'percent_change_classification': class_weights_percent_change,
# 'leg_direction': {} # Add if needed
}
# Modify model.fit to include class_weight
history = model.fit(
X_train,
{
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction']
},
epochs=200,
batch_size=32,
validation_split=0.2,
class_weight=class_weight_dict, # Add this line
callbacks=[early_stopping, reduce_lr] # Add your callbacks here
)
Use Resampling Techniques:
Oversampling Minority Classes: Techniques like SMOTE (Synthetic Minority Over-sampling Technique) can be employed to generate synthetic samples for minority classes.
Undersampling Majority Classes: Reduce the number of samples in the majority class to balance the dataset.
However, with sequential data, resampling needs to be applied carefully to maintain temporal dependencies.
Data Augmentation:
Introduce variations in the data to increase the diversity of the training dataset, which can help the model generalize better.
b. Simplifying the Model
Consider reducing the complexity of your Transformer model:
Fewer Transformer Blocks: Decreasing the number of transformer blocks can reduce overfitting.
Smaller Head Size and FF Dimensions: Adjusting these parameters can help in creating a less complex model.
c. Enhancing Regularization
Increase Dropout Rates:
Higher dropout rates can prevent the model from relying too heavily on specific neurons, promoting better generalization.
python
# Example: Increase dropout to 0.5
dropout=0.5
L2 Regularization:
Ensure you have adequate L2 regularization to penalize large weights.
d. Improving Evaluation Metrics and Training Strategy
Use Appropriate Metrics:
Incorporate metrics like macro-averaged F1-score, precision, and recall to get a better understanding of model performance across all classes.
Modify the early stopping criteria to monitor a more balanced metric, such as the macro F1-score for percent_change_classification.
python
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor='val_percent_change_classification_precision', # Consider using other metrics
patience=10,
restore_best_weights=True
)
Use Stratified Splitting:
Ensure that both training and validation sets maintain the same class distribution. Your existing train_test_split with stratify is appropriate.
e. Fine-Tuning Learning Rates and Optimizer
Experiment with different learning rates and optimizers. Sometimes, a lower learning rate can result in better convergence, especially in complex models.
Combine predictions from multiple models to improve robustness and generalization. Techniques like bagging or stacking can be beneficial.
4. Implementation Adjustments
Let's incorporate the recommended solutions into your existing code.
a. Incorporate Class Weights in Training
Modify the main() function to include class weights during model.fit:
python
b. Adjusting Evaluation Metrics
In your classification report generation, consider using more informative metrics:
python
from sklearn.metrics import classification_report, confusion_matrix, f1_score, precision_score, recall_score
# After predictions
predicted_classes = np.argmax(predictions['percent_change_classification'], axis=1)
print("Classification Report for 'percent_change_classification':")
print(classification_report(Y_test['percent_change_classification'], predicted_classes, target_names=[
'Down a Lot', 'Down Moderate', 'Down a Little', 'No Change', 'Up a Little', 'Up Moderate', 'Up a Lot']))
# Calculate macro F1-score
macro_f1 = f1_score(Y_test['percent_change_classification'], predicted_classes, average='macro')
print(f"Macro F1-Score: {macro_f1:.4f}")
c. Simplifying the Model
If overfitting persists, consider reducing the number of transformer blocks or the dimensionality:
python
# Example: Reduce transformer blocks to 2
model = build_enhanced_transformer_model(
input_shape=input_shape,
num_classes_classification=num_classes,
head_size=64,
num_heads=4,
ff_dim=128,
num_transformer_blocks=2, # Reduced from 4
dropout=0.5,
l2_reg=1e-4
)
d. Alternative Architectures
While Transformers are powerful, they might be overkill for certain tasks. Consider experimenting with simpler architectures like LSTM or GRU networks, which are often effective for sequential data.
5. Additional Recommendations
a. Monitoring Per-Class Performance
Implement callbacks or custom metrics to monitor the performance of each class separately. This can provide deeper insights into how well the model is learning each class.
b. Hyperparameter Tuning
Utilize tools like Keras Tuner, Optuna, or Hyperopt to systematically search for optimal hyperparameters, such as learning rates, dropout rates, and transformer dimensions.
c. Cross-Validation
Implement cross-validation to ensure that the model's performance is consistent across different subsets of the data.
d. Feature Engineering
Re-examine the features used. Sometimes, adding more informative features or removing noisy ones can significantly enhance model performance.
e. Ensemble Techniques
Combine predictions from multiple models to mitigate individual model weaknesses. Techniques like bagging, boosting, or stacking can be beneficial.
f. Data Quality and Quantity
Ensure that the data being fed into the model is of high quality. Additionally, increasing the size of the dataset can help the model generalize better.
6. Example Revised Code Snippets
Below are revised sections of your code incorporating some of the recommendations:
a. Incorporating Class Weights and Adjusting Callbacks
python
# Calculate class weights
from collections import Counter
counter = Counter(Y_percent_change)
print("Class distribution for 'percent_change_classification':", counter)
total = sum(counter.values())
class_weights_percent_change = {cls: total / (len(counter) * count) for cls, count in counter.items()}
print("Class Weights:", class_weights_percent_change)
class_weight_dict = {
'percent_change_classification': class_weights_percent_change,
# 'leg_direction': {} # Assuming 'leg_direction' is balanced
}
# Adjust early stopping to monitor macro F1-score (requires custom callback)
from tensorflow.keras.callbacks import Callback
from sklearn.metrics import f1_score
class F1ScoreCallback(Callback):
def __init__(self, validation_data):
super(F1ScoreCallback, self).__init__()
self.validation_data = validation_data
def on_epoch_end(self, epoch, logs=None):
X_val, Y_val = self.validation_data
Y_pred = self.model.predict(X_val)
Y_pred_classes = np.argmax(Y_pred['percent_change_classification'], axis=1)
f1 = f1_score(Y_val['percent_change_classification'], Y_pred_classes, average='macro')
print(f' - val_f1_score: {f1:.4f}')
if f1 > 0.8: # Example threshold
self.model.stop_training = True
# Instantiate the callback
f1_callback = F1ScoreCallback(validation_data=(X_test, Y_test))
# Modify model.fit to include class weights and callbacks
history = model.fit(
X_train,
{
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction']
},
epochs=200,
batch_size=32,
validation_split=0.2,
class_weight=class_weight_dict,
callbacks=[early_stopping, reduce_lr, f1_callback]
)
b. Reducing Model Complexity
python
# For example, reducing the number of transformer blocks and adjusting head size
model = build_enhanced_transformer_model(
input_shape=input_shape,
num_classes_classification=num_classes,
head_size=32, # Reduced from 64
num_heads=4,
ff_dim=64, # Reduced from 128
num_transformer_blocks=2, # Reduced from 4
dropout=0.5,
l2_reg=1e-4
)
c. Implementing a Custom F1 Score Monitor (Advanced)
Alternatively, you can create a custom callback to monitor the F1-score and use it for early stopping.
python
class F1Callback(Callback):
def __init__(self, validation_data, patience=10):
super(F1Callback, self).__init__()
self.X_val, self.Y_val = validation_data
self.best_f1 = 0
self.patience = patience
self.counter = 0
def on_epoch_end(self, epoch, logs=None):
Y_pred = self.model.predict(self.X_val)
Y_pred_classes = np.argmax(Y_pred['percent_change_classification'], axis=1)
Y_true = self.Y_val['percent_change_classification']
f1 = f1_score(Y_true, Y_pred_classes, average='macro')
print(f' - val_macro_f1: {f1:.4f}')
if f1 > self.best_f1:
self.best_f1 = f1
self.counter = 0
# Optionally, save the best model here
else:
self.counter += 1
if self.counter >= self.patience:
print("Early stopping due to no improvement in F1-score.")
self.model.stop_training = True
# Usage
f1_callback = F1Callback(validation_data=(X_test, Y_test), patience=10)
7. Conclusion
Your model's underperformance in percent_change_classification is primarily due to class imbalance and overfitting. By implementing class weighting, adjusting the model's complexity, enhancing regularization, and employing more informative evaluation metrics, you can significantly improve performance. Additionally, considering alternative architectures and leveraging ensemble methods can further bolster your model's robustness and generalization capabilities.
Remember, iterative experimentation and continuous monitoring are key. Adjust hyperparameters, try different techniques, and rigorously evaluate the model to achieve optimal performance.
If you encounter further issues or need more specific guidance on any of these steps, feel free to reach out!
Not yet included in a published release.
def main():
# ... [existing code] ...
# Address Class Imbalance
from collections import Counter
counter = Counter(Y_percent_change)
print("Class distribution for 'percent_change_classification':", counter)
# Calculate class weights
total = sum(counter.values())
class_weights = {cls: total / (len(counter) * count) for cls, count in counter.items()}
print("Class Weights:", class_weights)
# Split data
print("Splitting data into training and testing sets...")
X_train, X_test, y_percent_change_train, y_percent_change_test, y_leg_direction_train, y_leg_direction_test = train_test_split(
X,
Y_percent_change,
Y_leg_direction,
test_size=0.2,
random_state=42,
stratify=Y_percent_change # Ensure stratified split for classification
)
# Reassemble Y_train and Y_test dictionaries
Y_train = {
'percent_change_classification': y_percent_change_train,
'leg_direction': y_leg_direction_train
}
Y_test = {
'percent_change_classification': y_percent_change_test,
'leg_direction': y_leg_direction_test
}
# Prepare class weights for 'percent_change_classification'
class_weights_percent_change = class_weights # From your existing calculation
# Assemble class weights for multi-output
class_weight_dict = {
'percent_change_classification': class_weights_percent_change,
# 'leg_direction': {} # Add if needed
}
# Build and compile model
print("Building the Enhanced Transformer model...")
input_shape = (SEQ_LENGTH, X.shape[2]) # (60, num_features)
num_classes = len(np.unique(Y_percent_change)) # Should be 7
model = build_enhanced_transformer_model(
input_shape=input_shape,
num_classes_classification=num_classes,
head_size=64,
num_heads=4,
ff_dim=128,
num_transformer_blocks=4,
dropout=0.5, # Increased dropout
l2_reg=1e-4
)
model = compile_enhanced_multi_output_model(model, learning_rate=1e-4) # Lower learning rate
# Print model summary
print("Model Summary:")
model.summary()
# Implement Early Stopping and Learning Rate Scheduler
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor='val_percent_change_classification_recall', # Monitor recall for minority classes
patience=10,
restore_best_weights=True
)
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(
monitor='val_percent_change_classification_recall',
factor=0.5,
patience=5,
verbose=1
)
# Train model with class weights and callbacks
print("Training the model...")
history = model.fit(
X_train,
{
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction']
},
epochs=200,
batch_size=32,
validation_split=0.2,
class_weight=class_weight_dict, # Add class weights
callbacks=[early_stopping, reduce_lr]
)
# ... [rest of the code] ...