Total loss: 9.4880
Main Metric (compile_metrics): 2.6774
leg_direction_loss: 6.8888
percent_change_classification_loss: 0.6236
Classification Report for 'percent_change_classification'
The report provides a breakdown of the model's performance in terms of precision, recall, and F1-score for each class label (0–5).
code
Precision (how many selected items are relevant):
Class 4 has the highest precision at 0.37, while other classes (0, 1, 2, and 5) are low (around 0.12–0.14).
Recall (how many relevant items are selected):
Class 4 performs better than others with a recall of 0.48, indicating the model is relatively more accurate in identifying this class.
F1-Score (the harmonic mean of precision and recall):
The F1-scores are low across all classes, with Class 4 having the highest at 0.42.
Accuracy: 0.26 (26%), meaning the model correctly classifies only 26% of the test instances overall.
Macro Average: Averaging across all classes yields a precision, recall, and F1-score around 0.18–0.19.
Weighted Average: When accounting for class support, the weighted averages are slightly better, especially in recall and F1-score (around 0.25–0.26).
Summary
The model appears to struggle in differentiating among classes, as evidenced by low precision, recall, and F1-scores. It performs slightly better on Class 4 but is largely inaccurate on other classes. This result suggests that the model may require further tuning, data balancing, or additional features to improve its performance.
The training performance looks strong, but the validation metrics tell a different story:
code
Assistant
Percent Change Classification Loss and Accuracy:
Training Loss decreases steadily, reaching a low value, and Training Accuracy is high (near 1.0), suggesting the model has fit well on the training data.
However, Validation Loss increases over time, and Validation Accuracy remains low and flat (around 0.3), indicating overfitting. The model is not generalizing well to unseen data for this classification task.
Leg Direction Loss and Accuracy:
Training Loss decreases substantially, and Training Accuracy reaches almost 1.0, showing effective learning on training data.
Similar to the percent change classification, the Validation Loss is high and volatile, and Validation Accuracy remains low (around 0.7). This again points to overfitting, where the model memorizes training data but struggles with validation data.
Conclusion
While training performance appears good, the persistent gap and low performance on validation data indicate overfitting. Regularization techniques, a simpler model architecture, or additional data might help improve generalization. import os
Disable GPU to avoid CUDA-related errors
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
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=64,
num_heads=4,
ff_dim=128,
num_transformer_blocks=4,
dropout=0.1,
l2_reg=1e-4
):
"""
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=1000,
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 metrics and the provided code, it appears that your model is experiencing significant overfitting and poor generalization on the validation data, particularly for the percent_change_classification task. Below are detailed recommendations to help you diagnose and improve your model's performance.
1. Understanding the Current Issues
Overfitting Indicators:
Training vs. Validation Performance:
Training Accuracy: Near 1.0 (100%) for both tasks.
Validation Accuracy: Low and flat (~26% for classification and ~70% for leg direction).
Validation Loss: Increasing over epochs while training loss decreases.
Classification Performance Issues:
Low Precision, Recall, and F1-scores across most classes.
Only Class 4 shows relatively better performance.
2. Addressing Overfitting
a. Reduce Model Complexity
Your current Transformer model is quite complex, which might be unnecessary for the given dataset size and feature set.
Simplify the Architecture:
Reduce the Number of Transformer Blocks: Start with 1-2 blocks instead of 4.
Decrease head_size and ff_dim: Smaller dimensions can help prevent overfitting.
python
def build_simpler_transformer_model(...):
# Adjust parameters for a simpler model
head_size=32,
ff_dim=64,
num_transformer_blocks=2,
...
b. Increase Regularization
Enhance Dropout Rates:
Increase Dropout: From 0.1 to 0.3 or higher.
python
x = Dropout(0.3)(x)
Apply L2 Regularization More Aggressively:
python
kernel_regularizer=tf.keras.regularizers.l2(1e-3)
Add Dropout in More Layers: Especially after dense layers.
c. Utilize Early Stopping and Learning Rate Schedulers Effectively
Monitor Appropriate Metrics:
For multi-output models, ensure early stopping monitors the metric most critical to your task. For example:
d. Increase Training Data or Use Data Augmentation
Collect More Data: If possible, gather more historical data to provide the model with a broader range of market conditions.
Data Augmentation Techniques:
Adding Noise: Slightly perturb the features to create more diverse samples.
Synthetic Data Generation: Use methods like SMOTE for oversampling minority classes.
3. Improving Classification Performance
a. Re-evaluate Target Classification Strategy
Simplify Class Labels:
Current Setup: 7 classes may be too granular.
Recommendation: Combine similar classes to reduce complexity (e.g., merge "Up a Little" and "Up Moderate").
python
def classify(x, p):
if x < p[0.05]:
return 'Down a Lot'
elif x < p[0.2]:
return 'Down Moderate'
elif x < p[0.4]:
return 'Down a Little'
elif x < p[0.6]:
return 'No Change'
elif x < p[0.8]:
return 'Up Little/Moderate'
else:
return 'Up a Lot'
Binary Classification: If multi-class classification remains problematic, consider switching to binary classification (e.g., significant up vs. significant down vs. neutral).
b. Address Class Imbalance More Effectively
Class Weight Adjustments:
Ensure that classes are weighted inversely proportional to their frequency.
Ensure that all technical indicators used are relevant and not introducing noise.
Incorporate Additional Features:
Volume Indicators: Such as On-Balance Volume (OBV).
Sentiment Analysis: If possible, include sentiment scores from news or social media.
Feature Selection:
Use techniques like Recursive Feature Elimination (RFE) or feature importance from tree-based models to identify and retain the most predictive features.
d. Optimize Encoding and Scaling
Ensure Correct Encoding:
Validate that categorical features are appropriately encoded without introducing unintended ordinal relationships.
Consistent Scaling:
Apply scaling after splitting the data to prevent data leakage.
4. Refining the Model Architecture
a. Explore Alternative Architectures
Recurrent Neural Networks (RNNs):
LSTM or GRU Layers: Can effectively capture temporal dependencies in financial data.
python
from tensorflow.keras.layers import LSTM
def build_lstm_model(input_shape, num_classes):
model = tf.keras.Sequential([
LSTM(64, input_shape=input_shape, return_sequences=True),
Dropout(0.3),
LSTM(32),
Dropout(0.3),
Dense(64, activation='relu'),
Dropout(0.3),
Dense(num_classes, activation='softmax', name='percent_change_classification'),
Dense(1, activation='sigmoid', name='leg_direction')
])
return model
Convolutional Neural Networks (CNNs):
1D Convolutions: To capture local patterns in sequences.
python
from tensorflow.keras.layers import Conv1D, MaxPooling1D
def build_cnn_model(input_shape, num_classes):
inputs = Input(shape=input_shape)
x = Conv1D(64, kernel_size=3, activation='relu')(inputs)
x = MaxPooling1D(pool_size=2)(x)
x = Dropout(0.3)(x)
x = Conv1D(128, kernel_size=3, activation='relu')(x)
x = MaxPooling1D(pool_size=2)(x)
x = Dropout(0.3)(x)
x = GlobalAveragePooling1D()(x)
x = Dense(64, activation='relu')(x)
x = Dropout(0.3)(x)
percent_change_output = Dense(num_classes, activation='softmax', name='percent_change_classification')(x)
leg_direction_output = Dense(1, activation='sigmoid', name='leg_direction')(x)
model = Model(inputs=inputs, outputs=[percent_change_output, leg_direction_output])
return model
b. Modify Existing Transformer Model
Integrate Batch Normalization:
Can help stabilize and accelerate training.
python
from tensorflow.keras.layers import BatchNormalization
x = BatchNormalization()(x_norm)
Adjust Positional Encoding:
Ensure that the positional encoding aligns well with the sequence length and model's capacity.
c. Multi-Task Learning Considerations
Separate Loss Weights:
Assign different weights to each task's loss to prioritize one over the other.
Ensure that sequences are prepared correctly without introducing shifted labels or misalignments.
Handle Missing Data:
Impute or remove missing values effectively to prevent noise.
7. Monitoring and Evaluation Enhancements
a. Detailed Metrics
Use Additional Metrics:
Confusion Matrix: Helps identify specific class misclassifications.
Precision-Recall Curves: Especially useful for imbalanced datasets.
ROC-AUC Scores: For binary classification tasks.
b. Visualization
Learning Curves:
Plot training and validation loss and accuracy over epochs to visualize overfitting or underfitting.
Class Distribution:
Visualize to ensure that class imbalance is effectively addressed.
c. Error Analysis
Analyze Misclassified Samples:
Identify patterns or commonalities in the data where the model fails.
Feature Importance:
Use techniques like SHAP or LIME to understand which features influence predictions the most.
8. Code Enhancements and Best Practices
a. Modularize Loss and Metrics Handling
Ensure that each output's loss and metrics are effectively handled, especially when dealing with multi-output models.
b. Save and Load Preprocessing Objects
python
# Save 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)
# Later, load them as needed
with open('label_encoders.pkl', 'rb') as f:
label_encoders = pickle.load(f)
with open('scalers.pkl', 'rb') as f:
scalers = pickle.load(f)
c. Ensure Reproducibility
Set random seeds for reproducibility.
python
import tensorflow as tf
import numpy as np
import random
import os
def set_seed(seed=42):
np.random.seed(seed)
tf.random.set_seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
set_seed(42)
d. Optimize Data Loading
Batch Processing:
If the dataset is large, consider using generators or tf.data pipelines for efficient data handling.
e. Handle Class Labels Appropriately
Ensure that the class labels are correctly mapped and consistent across encoding and model predictions.
9. Potential Model Architecture Alternatives
Given that Transformers might be overkill for this task, explore simpler architectures to benchmark performance.
a. Bidirectional LSTM
python
from tensorflow.keras.layers import Bidirectional
def build_bidirectional_lstm(input_shape, num_classes):
inputs = Input(shape=input_shape)
x = Bidirectional(LSTM(64, return_sequences=True))(inputs)
x = Dropout(0.3)(x)
x = Bidirectional(LSTM(32))(x)
x = Dropout(0.3)(x)
x = Dense(64, activation='relu')(x)
x = Dropout(0.3)(x)
percent_change_output = Dense(num_classes, activation='softmax', name='percent_change_classification')(x)
leg_direction_output = Dense(1, activation='sigmoid', name='leg_direction')(x)
model = Model(inputs=inputs, outputs=[percent_change_output, leg_direction_output])
return model
b. Convolutional Neural Network (CNN)
Effective for Capturing Local Patterns:
python
def build_cnn_model(input_shape, num_classes):
inputs = Input(shape=input_shape)
x = Conv1D(64, kernel_size=3, activation='relu')(inputs)
x = MaxPooling1D(pool_size=2)(x)
x = Dropout(0.3)(x)
x = Conv1D(128, kernel_size=3, activation='relu')(x)
x = MaxPooling1D(pool_size=2)(x)
x = Dropout(0.3)(x)
x = GlobalAveragePooling1D()(x)
x = Dense(64, activation='relu')(x)
x = Dropout(0.3)(x)
percent_change_output = Dense(num_classes, activation='softmax', name='percent_change_classification')(x)
leg_direction_output = Dense(1, activation='sigmoid', name='leg_direction')(x)
model = Model(inputs=inputs, outputs=[percent_change_output, leg_direction_output])
return model
10. Final Recommendations
Start Simple: Before leveraging complex Transformer architectures, establish a strong baseline with simpler models like LSTM or CNN. This will help you understand whether the complexity of the Transformer is justified.
Iterative Approach: Implement changes incrementally. Adjust one aspect at a time (e.g., reduce model complexity, then increase regularization) to isolate effects and understand their impact.
Comprehensive Evaluation: Use various metrics and visualizations to gain insights into model performance beyond just accuracy and loss.
Documentation and Tracking: Keep track of experiments, hyperparameters, and results to systematically identify what works best.
Consult Literature: Review recent research on financial time series classification to incorporate state-of-the-art techniques and best practices.
By systematically applying these recommendations, you should be able to mitigate overfitting and enhance the classification performance of your model. Remember, model development is an iterative process that benefits greatly from experimentation and continuous evaluation.
Feel free to reach out with specific questions or updates on your progress!