Provide a Python data science project boilerplate using DVC for data version control. Large datasets should be stored in S3/GCS with only .dvc metadata in Git. Include a dvc.yaml pipeline that reproduces training steps.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import logging
import json
from pathlib import Path
import pandas as pd
import numpy as np
from src.config import get_config, DATA_DIR
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
def download_data():
"""
Download or prepare raw data.
In production, replace with actual download logic (S3, API, etc.)
"""
config = get_config()
raw_path = DATA_DIR / config.get('data.raw_path')
raw_path.mkdir(parents=True, exist_ok=True)
# Example: Create synthetic data
logger.info("Preparing raw data...")
# Training data
n_train = 10000
X_train = np.random.randn(n_train, 20)
y_train = (np.sum(X_train[:, :5], axis=1) > 0).astype(int)
train_df = pd.DataFrame(
X_train,
columns=[f"feature_{i}" for i in range(X_train.shape[1])]
)
train_df['target'] = y_train
train_df.to_csv(raw_path / 'train.csv', index=False)
logger.info(f"Train data: {train_df.shape}")
# Test data
n_test = 2000
X_test = np.random.randn(n_test, 20)
y_test = (np.sum(X_test[:, :5], axis=1) > 0).astype(int)
test_df = pd.DataFrame(
X_test,
columns=[f"feature_{i}" for i in range(X_test.shape[1])]
)
test_df['target'] = y_test
test_df.to_csv(raw_path / 'test.csv', index=False)
logger.info(f"Test data: {test_df.shape}")
logger.info(f"Data saved to {raw_path}")
if __name__ == "__main__":
download_data()
src/data/preprocess.py
python
import logging
import json
from pathlib import Path
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from src.config import get_config, DATA_DIR
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
def load_raw_data(config):
"""Load raw data"""
raw_path = DATA_DIR / config.get('data.raw_path')
train_df = pd.read_csv(raw_path / 'train.csv')
test_df = pd.read_csv(raw_path / 'test.csv')
return train_df, test_df
def preprocess_data(train_df: pd.DataFrame, test_df: pd.DataFrame, config):
"""Apply preprocessing transformations"""
params = config.get('preprocessing')
logger.info("Starting preprocessing...")
# Handle missing values
if params.get('handle_missing') == 'mean':
train_df = train_df.fillna(train_df.mean())
test_df = test_df.fillna(test_df.mean())
# Remove outliers
if params.get('remove_outliers'):
threshold = params.get('outlier_threshold', 3.0)
numeric_cols = train_df.select_dtypes(include=[np.number]).columns
for col in numeric_cols:
if col != 'target':
mean = train_df[col].mean()
std = train_df[col].std()
mask = np.abs((train_df[col] - mean) / std) <= threshold
train_df = train_df[mask]
# Normalize
if params.get('normalize'):
numeric_cols = [col for col in train_df.columns if col != 'target']
scaler = StandardScaler()
train_df[numeric_cols] = scaler.fit_transform(train_df[numeric_cols])
test_df[numeric_cols] = scaler.transform(test_df[numeric_cols])
return train_df, test_df, scaler
def main():
"""Main preprocessing pipeline"""
config = get_config()
# Load data
train_df, test_df = load_raw_data(config)
logger.info(f"Loaded data - Train: {train_df.shape}, Test: {test_df.shape}")
# Preprocess
train_df, test_df, scaler = preprocess_data(train_df, test_df, config)
# Save processed data
processed_path = DATA_DIR / config.get('data.processed_path')
processed_path.mkdir(parents=True, exist_ok=True)
train_df.to_csv(processed_path / 'train.csv', index=False)
test_df.to_csv(processed_path / 'test.csv', index=False)
logger.info(f"Saved processed data to {processed_path}")
# Save statistics
stats = {
'train_shape': train_df.shape,
'test_shape': test_df.shape,
'columns': list(train_df.columns),
'dtypes': {col: str(dtype) for col, dtype in train_df.dtypes.items()}
}
Path('reports').mkdir(exist_ok=True)
with open('reports/preprocessing_stats.json', 'w') as f:
json.dump(stats, f, indent=2)
if __name__ == "__main__":
main()
src/data/validation.py
python
import logging
import json
from pathlib import Path
import pandas as pd
import numpy as np
from src.config import get_config, DATA_DIR
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
def validate_data():
"""Validate raw data quality"""
config = get_config()
raw_path = DATA_DIR / config.get('data.raw_path')
train_df = pd.read_csv(raw_path / 'train.csv')
validation_results = {
'total_rows': len(train_df),
'total_columns': len(train_df.columns),
'missing_values': train_df.isnull().sum().to_dict(),
'duplicates': len(train_df) - len(train_df.drop_duplicates()),
'dtypes': {col: str(dtype) for col, dtype in train_df.dtypes.items()}
}
logger.info(f"Data quality check: {validation_results}")
# Save report
Path('reports').mkdir(exist_ok=True)
with open('reports/data_quality.json', 'w') as f:
json.dump(validation_results, f, indent=2)
if __name__ == "__main__":
validate_data()
src/models/model.py
python
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
from typing import Literal
class ModelFactory:
"""Factory for creating different model types"""
@staticmethod
def create(model_type: str, params: dict):
"""Create model instance based on type"""
if model_type == 'random_forest':
rf_params = params.get('random_forest', {})
return RandomForestClassifier(**rf_params)
elif model_type == 'xgboost':
xgb_params = params.get('xgboost', {})
return xgb.XGBClassifier(**xgb_params)
else:
raise ValueError(f"Unknown model type: {model_type}")
src/models/train.py
python
src/evaluation/evaluate.py
python
import logging
import pickle
import json
from pathlib import Path
import pandas as pd
import numpy as np
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
roc_auc_score, roc_curve, precision_recall_curve
)
from src.config import get_config, DATA_DIR, MODELS_DIR
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
def load_model(model_path):
"""Load trained model"""
with open(model_path, 'rb') as f:
model = pickle.load(f)
return model
def evaluate():
"""Evaluate model on test set"""
config = get_config()
# Load model
model_path = MODELS_DIR / 'model.pkl'
model = load_model(model_path)
logger.info(f"Model loaded from {model_path}")
# Load test data
processed_path = DATA_DIR / config.get('data.processed_path')
test_df = pd.read_csv(processed_path / 'test.csv')
X_test = test_df.drop('target', axis=1)
y_test = test_df['target']
# Predictions
logger.info("Generating predictions...")
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:, 1]
# Calculate metrics
metrics = {
'accuracy': float(accuracy_score(y_test, y_pred)),
'precision': float(precision_score(y_test, y_pred)),
'recall': float(recall_score(y_test, y_pred)),
'f1': float(f1_score(y_test, y_pred)),
'roc_auc': float(roc_auc_score(y_test, y_pred_proba))
}
logger.info(f"Test metrics: {metrics}")
# Save metrics
Path('reports').mkdir(exist_ok=True)
with open('reports/eval_metrics.json', 'w') as f:
json.dump(metrics, f, indent=2)
# ROC curve
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
roc_data = {'fpr': fpr.tolist(), 'tpr': tpr.tolist()}
with open('reports/roc_auc.json', 'w') as f:
json.dump(roc_data, f, indent=2)
# Precision-Recall curve
precision, recall, _ = precision_recall_curve(y_test, y_pred_proba)
pr_data = {'precision': precision.tolist(), 'recall': recall.tolist()}
with open('reports/precision_recall.json', 'w') as f:
json.dump(pr_data, f, indent=2)
if __name__ == "__main__":
evaluate()
5. Requirements
requirements.txt
txt
# Core
numpy>=1.21.0
pandas>=1.3.0
scikit-learn>=1.0.0
# ML frameworks
xgboost>=1.5.0
lightgbm>=3.3.0
# DVC
dvc[s3]>=2.14.0
# Or for GCS: dvc[gs]>=2.14.0
# Cloud storage
boto3>=1.24.0 # For S3
google-cloud-storage>=2.5.0 # For GCS
# Configuration
pyyaml>=6.0
# Development
pytest>=7.0
pytest-cov>=3.0
black>=22.0
flake8>=4.0
mypy>=0.950
# Visualization
matplotlib>=3.5.0
seaborn>=0.11.0
plotly>=5.0.0
# Jupyter
jupyter>=1.0.0
notebook>=6.4.0