import os
import json
import gc
import pandas as pd
import numpy as np
from tqdm import tqdm
from numerapi import NumerAPI
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Ridge
import matplotlib.pyplot as plt
import seaborn as sns
from itertools import combinations
feature_names = [f for f in train.columns if "feature_" in f]
feature_names = [f for f in feature_names if f in features_to_load]
target_names = ["target"]
for feature in feature_names:
for lag in lags:
lag_col_name = f'{feature}lag{lag}'
lag_train[lag_col_name] = df_train.groupby(group_col)[feature].shift(lag)
lag_validation[lag_col_name] = df_validation.groupby(group_col)[feature].shift(lag)
# Convert dictionaries to DataFrames
lag_train_df = pd.DataFrame(lag_train, index=df_train.index)
lag_validation_df = pd.DataFrame(lag_validation, index=df_validation.index)
# Concatenate to original DataFrames
df_train = pd.concat([df_train, lag_train_df], axis=1)
df_validation = pd.concat([df_validation, lag_validation_df], axis=1)
# Drop rows with any NaN values resulted from lagging
df_train = df_train.dropna().reset_index(drop=True)
df_validation = df_validation.dropna().reset_index(drop=True)
return df_train, df_validation
# Evaluate all remaining features in parallel
tqdm_features = tqdm(remaining_features, desc="Evaluating features", leave=False)
for feature in tqdm_features:
current_features = selected_features + [feature]
X = train[current_features].values
performance = evaluate_performance(X, y, model)
temp_performances[feature] = performance
if performance > best_performance:
best_performance = performance
best_feature = feature
if best_feature is None:
break
selected_features.append(best_feature)
remaining_features.remove(best_feature)
performance_history.append(best_performance)
print(f"Selected Feature: {best_feature}, Current Performance: {best_performance:.4f}")
# Check for improvement
if len(performance_history) > 1:
improvement = performance_history[-1] - performance_history[-2]
if improvement < 0.001:
print(f"Improvement {improvement:.6f} is less than threshold. Stopping feature selection.")
break
plt.figure(figsize=(12, 6))
sns.lineplot(x=range(1, len(performance_history)+1), y=performance_history, marker='o')
plt.title('Feature Selection Progress')
plt.xlabel('Number of Features Selected')
plt.ylabel('Cross-Validated R²')
plt.grid(True)
plt.show()
Analyzing the Results
final_performance = performance_history[-1] if performance_history else None
if final_performance is not None:
print(f"\nFinal Performance with {len(selected_features)} Features: R² = {final_performance:.4f}")
else:
print("\nNo features were selected.")
if selected_features:
model.fit(train[selected_features], y)
coefficients = pd.Series(model.coef, index=selected_features).sort_values(ascending=False)
else:
print("No features were selected to fit the model.") This is my jupuyter notebook, optimize it for less memory usage, add checkpoints to resume work, because is consumption is too high (800gb ram)
Optimizing your Jupyter notebook for lower memory usage and adding checkpoints to allow resuming work can significantly improve efficiency and prevent memory-related crashes. Below are detailed steps and code modifications to achieve these goals:
Optimize Data Types: Use more memory-efficient data types for your DataFrame columns.
Efficient Feature Generation: Streamline feature generation to minimize memory overhead.
Implement Checkpoints: Save intermediate states to disk to resume processing without starting from scratch.
General Memory Optimization: Avoid unnecessary DataFrame copies and manage garbage collection effectively.
Below is the revised and optimized version of your notebook with detailed explanations.
1. Optimize Data Types
Reducing the memory footprint by converting columns to more efficient data types can lead to significant savings. For example, use float32 instead of float64 and int8 or int16 instead of larger integer types where appropriate.
python
import os
import json
import gc
import pandas as pd
import numpy as np
from tqdm import tqdm
from numerapi import NumerAPI
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Ridge
import matplotlib.pyplot as plt
import seaborn as sns
from itertools import combinations
import joblib # For checkpointing
# Initialize NumerAPI
api = NumerAPI()
# Ensure the data directory exists
os.makedirs("../data", exist_ok=True)
# Define checkpoint file paths
CHECKPOINT_PATH = "../data/checkpoints/"
os.makedirs(CHECKPOINT_PATH, exist_ok=True)
# Download datasets only if not already downloaded
dataset_files = {
"train.parquet": "v5.0/train.parquet",
"validation.parquet": "v5.0/validation.parquet",
"validation_example_preds.parquet": "v5.0/validation_example_preds.parquet",
"features.json": "v5.0/features.json",
"train_benchmark_models.parquet": "v5.0/train_benchmark_models.parquet",
"validation_benchmark_models.parquet": "v5.0/validation_benchmark_models.parquet"
}
for filename, dataset in dataset_files.items():
filepath = f"../data/{filename}"
if not os.path.exists(filepath):
api.download_dataset(dataset, filepath)
print(f"Downloaded {filename}")
else:
print(f"{filename} already exists. Skipping download.")
Function to Optimize Data Types
python
def optimize_dtypes(df, float_cols=None, int_cols=None):
"""
Optimizes the data types of a DataFrame to reduce memory usage.
Parameters:
df (pd.DataFrame): The DataFrame to optimize.
float_cols (list): Columns to convert to float32.
int_cols (list): Columns to convert to smallest possible integer categories.
Returns:
pd.DataFrame: Optimized DataFrame.
"""
for col in df.columns:
if df[col].dtype == 'float64' and (float_cols is None or col in float_cols):
df[col] = df[col].astype('float32')
elif df[col].dtype == 'int64' and (int_cols is None or col in int_cols):
# Downcast integers
df[col] = pd.to_numeric(df[col], downcast='integer')
return df
Load and Optimize Data
python
# Load features metadata
with open("../data/features.json") as f:
features_meta = json.load(f)
# Select the "all" feature set
features_to_load = features_meta["feature_sets"]["all"]
# Define columns to load
common_columns = ["era", "data_type", "target"]
train_columns = features_to_load + common_columns
validation_columns = features_to_load + common_columns
# Function to load data with dtype optimization
def load_data(file_path, columns, optimize=True):
df = pd.read_parquet(file_path, columns=columns)
if optimize:
df = optimize_dtypes(df)
return df
# Checkpoints
train_checkpoint = os.path.join(CHECKPOINT_PATH, "train_preprocessed.pkl")
validation_checkpoint = os.path.join(CHECKPOINT_PATH, "validation_preprocessed.pkl")
if os.path.exists(train_checkpoint) and os.path.exists(validation_checkpoint):
print("Loading preprocessed data from checkpoints...")
train = joblib.load(train_checkpoint)
validation = joblib.load(validation_checkpoint)
else:
print("Loading and preprocessing data...")
train = load_data("../data/train.parquet", train_columns)
validation = load_data("../data/validation.parquet", validation_columns)
# Convert 'era' column to integer codes with category optimization
for df in [train, validation]:
df['era_int'] = df['era'].astype('category').cat.codes
# Fill missing values in features with -2
feature_names = [f for f in features_to_load if f in train.columns and "feature_" in f]
print("Filling missing feature values...")
train[feature_names] = train[feature_names].fillna(-2).astype('float32')
validation[feature_names] = validation[feature_names].fillna(-2).astype('float32')
# Fill missing target values with 0.5 (if applicable)
target_names = ["target"]
train[target_names] = train[target_names].fillna(0.5).astype('float32')
validation[target_names] = validation[target_names].fillna(0.5).astype('float32')
# Drop rows with missing target values in validation set
validation = validation.dropna(subset=["target"]).reset_index(drop=True)
# Save to checkpoints
joblib.dump(train, train_checkpoint)
joblib.dump(validation, validation_checkpoint)
print("Preprocessed data saved to checkpoints.")
# Free memory
gc.collect()
print(f"Feature set: {len(feature_names)} features")
2. Efficient Feature Generation
a. Basic Statistical Features
Instead of creating new columns for each statistic, consider computing them on the fly or using memory-efficient methods. However, since you need these features for modeling, here's an optimized approach:
python
# Checkpoint paths
basic_stats_checkpoint = os.path.join(CHECKPOINT_PATH, "train_validation_basic_stats.pkl")
if os.path.exists(basic_stats_checkpoint):
print("Loading basic statistical features from checkpoint...")
train, validation = joblib.load(basic_stats_checkpoint)
else:
print("Generating Basic Statistical Features...")
def generate_basic_statistical_features(df_train, df_validation, feature_names):
# Precompute statistics to avoid repeated calculations
stats = {
'mean': df_train[feature_names].mean(),
'median': df_train[feature_names].median(),
'std': df_train[feature_names].std()
}
# Apply statistics to train
for stat_name, stat_values in stats.items():
for feature in feature_names:
new_col = f'{feature}_train_{stat_name}'
df_train[new_col] = stat_values[feature]
# Apply absolutes
df_train[[f'{f}_abs' for f in feature_names]] = df_train[feature_names].abs().astype('float32')
df_validation[[f'{f}_train_abs' for f in feature_names]] = df_validation[feature_names].abs().astype('float32')
return df_train, df_validation
train, validation = generate_basic_statistical_features(train, validation, feature_names)
# Save to checkpoint
joblib.dump((train, validation), basic_stats_checkpoint)
print("Basic statistical features saved to checkpoint.")
gc.collect()
b. Interaction Features
Generating all possible interaction features can exponentially increase memory usage. To mitigate this:
Limit Interaction Features: Instead of generating all n(n-1)/2 combinations, select a subset based on domain knowledge or feature importance.
On-the-Fly Generation: If possible, compute interaction features during model training instead of storing them.
Sparse Representations: Use sparse matrices if interactions are sparse.
However, assuming you need to generate and store them, here's an optimized approach with checkpointing and memory management:
Ensure that lag features are created efficiently and manage memory by processing in chunks if necessary.
python
lag_checkpoint = os.path.join(CHECKPOINT_PATH, "train_validation_lag_features.pkl")
if os.path.exists(lag_checkpoint):
print("Loading lag features from checkpoint...")
train, validation = joblib.load(lag_checkpoint)
else:
print("Generating Lag Features...")
def generate_lag_features(df_train, df_validation, feature_names, lags, group_col='era_int'):
for feature in tqdm(feature_names, desc="Generating lag features"):
for lag in lags:
lag_col_name = f'{feature}lag{lag}'
df_train[lag_col_name] = df_train.groupby(group_col)[feature].shift(lag).astype('float32')
df_validation[lag_col_name] = df_validation.groupby(group_col)[feature].shift(lag).astype('float32')
gc.collect()
# Drop rows with any NaN values resulted from lagging
df_train.dropna(inplace=True)
df_validation.dropna(inplace=True)
return df_train.reset_index(drop=True), df_validation.reset_index(drop=True)
lags = [1, 2, 3]
train, validation = generate_lag_features(train, validation, feature_names, lags)
# Save to checkpoint
joblib.dump((train, validation), lag_checkpoint)
print("Lag features saved to checkpoint.")
gc.collect()
# Defragment DataFrames by copying
print("Defragmenting DataFrames...")
train = train.copy()
validation = validation.copy()
gc.collect()
# Update feature list
all_features = [col for col in train.columns if col not in ['era', 'data_type', 'target', 'era_int']]
3. Feature Selection with Checkpoints and Memory Optimization
The feature selection loop is the most memory-intensive and time-consuming part. To optimize:
Cache Performance Metrics: Save performance metrics after each feature addition.
Parallel Processing: Parallelize feature evaluations where possible.
Early Stopping: Stop the process when improvements are below a threshold.
a. Define Checkpoints for Feature Selection
python
feature_selection_checkpoint = os.path.join(CHECKPOINT_PATH, "feature_selection.pkl")
if os.path.exists(feature_selection_checkpoint):
print("Loading feature selection state from checkpoint...")
selected_features, performance_history, remaining_features = joblib.load(feature_selection_checkpoint)
else:
print("Starting Feature Selection...")
target = "target"
candidate_features = all_features.copy()
selected_features = []
remaining_features = candidate_features.copy()
performance_history = []
# Save initial state
joblib.dump((selected_features, performance_history, remaining_features), feature_selection_checkpoint)
b. Optimize the Feature Selection Loop
Use more efficient cross-validation and avoid repeated computations by caching.
python
if not os.path.exists(feature_selection_checkpoint) or not selected_features:
# Define Performance Metric
def evaluate_performance(X, y, model):
scores = cross_val_score(model, X, y, cv=5, scoring='r2', n_jobs=-1)
return scores.mean()
# Initialize model
model = Ridge(alpha=1.0)
y = train[target].values
while remaining_features:
best_feature = None
best_performance = -np.inf
temp_performances = {}
print(f"Evaluating {len(remaining_features)} remaining features...")
# Iterate through remaining features
for feature in tqdm(remaining_features, desc="Evaluating features"):
current_features = selected_features + [feature]
X = train[current_features].values
performance = evaluate_performance(X, y, model)
temp_performances[feature] = performance
if performance > best_performance:
best_performance = performance
best_feature = feature
if best_feature is None:
break
selected_features.append(best_feature)
remaining_features.remove(best_feature)
performance_history.append(best_performance)
print(f"Selected Feature: {best_feature}, Current Performance: {best_performance:.4f}")
# Save checkpoint
joblib.dump((selected_features, performance_history, remaining_features), feature_selection_checkpoint)
print("Feature selection state saved to checkpoint.")
# Check for improvement
if len(performance_history) > 1:
improvement = performance_history[-1] - performance_history[-2]
if improvement < 0.001:
print(f"Improvement {improvement:.6f} is less than threshold. Stopping feature selection.")
break
Note: The feature selection process can be very time-consuming, especially with a large number of features. Consider using more sophisticated feature selection methods like Recursive Feature Elimination (RFE) or feature importance from tree-based models if appropriate.
c. Load Feature Selection State
python
# Reload feature selection state after the loop
selected_features, performance_history, remaining_features = joblib.load(feature_selection_checkpoint)
plt.figure(figsize=(12, 6))
sns.lineplot(x=range(1, len(performance_history)+1), y=performance_history, marker='o')
plt.title('Feature Selection Progress')
plt.xlabel('Number of Features Selected')
plt.ylabel('Cross-Validated R²')
plt.grid(True)
plt.show()
c. Analyze Results and Plot Coefficients
python
# Analyzing the Results
final_performance = performance_history[-1] if performance_history else None
if final_performance is not None:
print(f"\nFinal Performance with {len(selected_features)} Features: R² = {final_performance:.4f}")
else:
print("\nNo features were selected.")
if selected_features:
model.fit(train[selected_features], y)
coefficients = pd.Series(model.coef_, index=selected_features).sort_values(ascending=False)
print("\nFeature Coefficients:")
print(coefficients)
# Plot Feature Coefficients
plt.figure(figsize=(12, 6))
coefficients.plot(kind='bar')
plt.title('Feature Coefficients in Ridge Regression')
plt.xlabel('Features')
plt.ylabel('Coefficient Value')
plt.tight_layout()
plt.show()
else:
print("No features were selected to fit the model.")
5. General Memory Optimization Tips
Avoid Inplace Operations: Although not always possible with pandas, refrain from using inplace operations as they can sometimes create temporary copies under the hood.
Delete Unused Variables: Explicitly delete large variables that are no longer needed using del variable_name followed by gc.collect().
Use Iterators: When dealing with large datasets, process data in chunks or use iterators to avoid loading everything into memory at once.
Leverage Memory Mapping: For extremely large datasets, consider using memory mapping techniques via libraries such as dask or pyarrow.
6. Additional Considerations
Use Dask for Out-of-Core Computing: If memory remains an issue, consider switching to dask.dataframe, which allows for out-of-core computations and can handle datasets larger than memory.
python
import dask.dataframe as dd
# Convert pandas DataFrame to dask DataFrame
train_dd = dd.from_pandas(train, npartitions=10)
validation_dd = dd.from_pandas(validation, npartitions=10)
Sparse Matrices: If many features are zeros or have a lot of missing values, using sparse matrices can save memory.
python
from scipy import sparse
X_sparse = sparse.csr_matrix(X)
Model Selection: Ridge regression may not require all features to be loaded into memory simultaneously. Explore models that support incremental learning, such as SGDRegressor, which can handle data in batches.
By implementing the above optimizations and checkpointing mechanisms, you should be able to significantly reduce memory consumption and make your workflow more robust against interruptions. Remember to monitor your memory usage regularly using tools like memory_profiler to identify and address any remaining bottlenecks.