1
---
2
name: ML Pipeline Automation
3
description: Build end-to-end ML pipelines with automated data processing, training, validation, and deployment using Airflow, Kubeflow, and Jenkins
4
---
5
6
# ML Pipeline Automation
7
8
ML pipeline automation orchestrates the entire machine learning workflow from data ingestion through model deployment, ensuring reproducibility, scalability, and reliability.
9
10
## Pipeline Components
11
12
- **Data Ingestion**: Collecting data from multiple sources
13
- **Data Processing**: Cleaning, transformation, feature engineering
14
- **Model Training**: Training and hyperparameter tuning
15
- **Validation**: Cross-validation and testing
16
- **Deployment**: Moving models to production
17
- **Monitoring**: Tracking performance metrics
18
19
## Orchestration Platforms
20
21
- **Apache Airflow**: Workflow scheduling with DAGs
22
- **Kubeflow**: Kubernetes-native ML workflows
23
- **Jenkins**: CI/CD for ML pipelines
24
- **Prefect**: Modern data flow orchestration
25
- **Dagster**: Asset-driven orchestration
26
27
## Python Implementation
28
29
```python
30
import pandas as pd
31
import numpy as np
32
from sklearn.datasets import make_classification
33
from sklearn.model_selection import train_test_split
34
from sklearn.preprocessing import StandardScaler
35
from sklearn.ensemble import RandomForestClassifier
36
from sklearn.metrics import accuracy_score, f1_score
37
import joblib
38
import logging
39
from datetime import datetime
40
import json
41
import os
42
43
# Airflow imports
44
from airflow import DAG
45
from airflow.operators.python import PythonOperator
46
from airflow.operators.bash import BashOperator
47
from airflow.utils.dates import days_ago
48
49
# MLflow for tracking
50
import mlflow
51
import mlflow.sklearn
52
53
# Logging setup
54
logging.basicConfig(level=logging.INFO)
55
logger = logging.getLogger(__name__)
56
57
print("=== 1. Modular Pipeline Functions ===")
58
59
# Data ingestion
60
def ingest_data(**context):
61
"""Ingest and load data"""
62
logger.info("Starting data ingestion...")
63
64
X, y = make_classification(n_samples=2000, n_features=30,
65
n_informative=20, random_state=42)
66
data = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(X.shape[1])])
67
data['target'] = y
68
69
# Save to disk
70
data_path = '/tmp/raw_data.csv'
71
data.to_csv(data_path, index=False)
72
73
context['task_instance'].xcom_push(key='data_path', value=data_path)
74
logger.info(f"Data ingested: {len(data)} rows")
75
return {'status': 'success', 'samples': len(data)}
76
77
# Data processing
78
def process_data(**context):
79
"""Clean and preprocess data"""
80
logger.info("Starting data processing...")
81
82
# Get data path from previous task
83
task_instance = context['task_instance']
84
data_path = task_instance.xcom_pull(key='data_path', task_ids='ingest_data')
85
86
data = pd.read_csv(data_path)
87
88
# Handle missing values
89
data = data.fillna(data.mean())
90
91
# Remove duplicates
92
data = data.drop_duplicates()
93
94
# Remove outliers (simple approach)
95
numeric_cols = data.select_dtypes(include=[np.number]).columns
96
for col in numeric_cols:
97
Q1 = data[col].quantile(0.25)
98
Q3 = data[col].quantile(0.75)
99
IQR = Q3 - Q1
100
data = data[(data[col] >= Q1 - 1.5 * IQR) & (data[col] <= Q3 + 1.5 * IQR)]
101
102
processed_path = '/tmp/processed_data.csv'
103
data.to_csv(processed_path, index=False)
104
105
task_instance.xcom_push(key='processed_path', value=processed_path)
106
logger.info(f"Data processed: {len(data)} rows after cleaning")
107
return {'status': 'success', 'rows_remaining': len(data)}
108
109
# Feature engineering
110
def engineer_features(**context):
111
"""Create new features"""
112
logger.info("Starting feature engineering...")
113
114
task_instance = context['task_instance']
115
processed_path = task_instance.xcom_pull(key='processed_path', task_ids='process_data')
116
117
data = pd.read_csv(processed_path)
118
119
# Create interaction features
120
feature_cols = [col for col in data.columns if col.startswith('feature_')]
121
for i in range(min(5, len(feature_cols))):
122
for j in range(i+1, min(6, len(feature_cols))):
123
data[f'interaction_{i}_{j}'] = data[feature_cols[i]] * data[feature_cols[j]]
124
125
# Create polynomial features
126
for col in feature_cols[:5]:
127
data[f'{col}_squared'] = data[col] ** 2
128
129
engineered_path = '/tmp/engineered_data.csv'
130
data.to_csv(engineered_path, index=False)
131
132
task_instance.xcom_push(key='engineered_path', value=engineered_path)
133
logger.info(f"Features engineered: {len(data.columns)} total features")
134
return {'status': 'success', 'features': len(data.columns)}
135
136
# Train model
137
def train_model(**context):
138
"""Train ML model"""
139
logger.info("Starting model training...")
140
141
task_instance = context['task_instance']
142
engineered_path = task_instance.xcom_pull(key='engineered_path', task_ids='engineer_features')
143
144
data = pd.read_csv(engineered_path)
145
146
X = data.drop('target', axis=1)
147
y = data['target']
148
149
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
150
151
# Scale features
152
scaler = StandardScaler()
153
X_train_scaled = scaler.fit_transform(X_train)
154
X_test_scaled = scaler.transform(X_test)
155
156
# Train model
157
model = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=42)
158
model.fit(X_train_scaled, y_train)
159
160
# Evaluate
161
y_pred = model.predict(X_test_scaled)
162
accuracy = accuracy_score(y_test, y_pred)
163
f1 = f1_score(y_test, y_pred)
164
165
# Save model
166
model_path = '/tmp/model.pkl'
167
scaler_path = '/tmp/scaler.pkl'
168
joblib.dump(model, model_path)
169
joblib.dump(scaler, scaler_path)
170
171
task_instance.xcom_push(key='model_path', value=model_path)
172
task_instance.xcom_push(key='scaler_path', value=scaler_path)
173
174
# Log to MLflow
175
with mlflow.start_run():
176
mlflow.log_param('n_estimators', 100)
177
mlflow.log_param('max_depth', 15)
178
mlflow.log_metric('accuracy', accuracy)
179
mlflow.log_metric('f1_score', f1)
180
mlflow.sklearn.log_model(model, 'model')
181
182
logger.info(f"Model trained: Accuracy={accuracy:.4f}, F1={f1:.4f}")
183
return {'status': 'success', 'accuracy': accuracy, 'f1_score': f1}
184
185
# Validate model
186
def validate_model(**context):
187
"""Validate model performance"""
188
logger.info("Starting model validation...")
189
190
task_instance = context['task_instance']
191
model_path = task_instance.xcom_pull(key='model_path', task_ids='train_model')
192
engineered_path = task_instance.xcom_pull(key='engineered_path', task_ids='engineer_features')
193
194
model = joblib.load(model_path)
195
data = pd.read_csv(engineered_path)
196
197
X = data.drop('target', axis=1)
198
y = data['target']
199
200
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
201
202
scaler_path = task_instance.xcom_pull(key='scaler_path', task_ids='train_model')
203
scaler = joblib.load(scaler_path)
204
X_test_scaled = scaler.transform(X_test)
205
206
# Validate
207
y_pred = model.predict(X_test_scaled)
208
accuracy = accuracy_score(y_test, y_pred)
209
210
validation_result = {
211
'status': 'success' if accuracy > 0.85 else 'failed',
212
'accuracy': accuracy,
213
'threshold': 0.85,
214
'timestamp': datetime.now().isoformat()
215
}
216
217
task_instance.xcom_push(key='validation_result', value=json.dumps(validation_result))
218
219
logger.info(f"Validation result: {validation_result}")
220
return validation_result
221
222
# Deploy model
223
def deploy_model(**context):
224
"""Deploy validated model"""
225
logger.info("Starting model deployment...")
226
227
task_instance = context['task_instance']
228
validation_result = json.loads(task_instance.xcom_pull(
229
key='validation_result', task_ids='validate_model'))
230
231
if validation_result['status'] != 'success':
232
logger.warning("Validation failed, deployment skipped")
233
return {'status': 'skipped', 'reason': 'validation_failed'}
234
235
model_path = task_instance.xcom_pull(key='model_path', task_ids='train_model')
236
scaler_path = task_instance.xcom_pull(key='scaler_path', task_ids='train_model')
237
238
# Simulate deployment
239
deploy_path = '/tmp/deployed_model/'
240
os.makedirs(deploy_path, exist_ok=True)
241
242
import shutil
243
shutil.copy(model_path, os.path.join(deploy_path, 'model.pkl'))
244
shutil.copy(scaler_path, os.path.join(deploy_path, 'scaler.pkl'))
245
246
logger.info(f"Model deployed to {deploy_path}")
247
return {'status': 'success', 'deploy_path': deploy_path}
248
249
# 2. Airflow DAG Definition
250
print("\n=== 2. Airflow DAG ===")
251
252
dag_definition = '''
253
from airflow import DAG
254
from airflow.operators.python import PythonOperator
255
from datetime import datetime, timedelta
256
257
default_args = {
258
'owner': 'ml-team',
259
'retries': 1,
260
'retry_delay': timedelta(minutes=5),
261
}
262
263
with DAG(
264
'ml_pipeline_dag',
265
default_args=default_args,
266
description='End-to-end ML pipeline',
267
schedule_interval='0 2 * * *', # Daily at 2 AM
268
start_date=datetime(2024, 1, 1),
269
catchup=False,
270
) as dag:
271
272
# Task 1: Ingest Data
273
ingest = PythonOperator(
274
task_id='ingest_data',
275
python_callable=ingest_data,
276
)
277
278
# Task 2: Process Data
279
process = PythonOperator(
280
task_id='process_data',
281
python_callable=process_data,
282
)
283
284
# Task 3: Engineer Features
285
engineer = PythonOperator(
286
task_id='engineer_features',
287
python_callable=engineer_features,
288
)
289
290
# Task 4: Train Model
291
train = PythonOperator(
292
task_id='train_model',
293
python_callable=train_model,
294
)
295
296
# Task 5: Validate Model
297
validate = PythonOperator(
298
task_id='validate_model',
299
python_callable=validate_model,
300
)
301
302
# Task 6: Deploy Model
303
deploy = PythonOperator(
304
task_id='deploy_model',
305
python_callable=deploy_model,
306
)
307
308
# Define dependencies
309
ingest >> process >> engineer >> train >> validate >> deploy
310
'''
311
312
print("Airflow DAG defined with 6 tasks")
313
314
# 3. Pipeline execution summary
315
print("\n=== 3. Pipeline Execution ===")
316
317
class PipelineOrchestrator:
318
def __init__(self):
319
self.execution_log = []
320
self.start_time = None
321
self.end_time = None
322
323
def run_pipeline(self):
324
self.start_time = datetime.now()
325
logger.info("Starting ML pipeline execution")
326
327
try:
328
# Execute pipeline tasks
329
result1 = ingest_data(task_instance=self)
330
self.execution_log.append(('ingest_data', result1))
331
332
result2 = process_data(task_instance=self)
333
self.execution_log.append(('process_data', result2))
334
335
result3 = engineer_features(task_instance=self)
336
self.execution_log.append(('engineer_features', result3))
337
338
result4 = train_model(task_instance=self)
339
self.execution_log.append(('train_model', result4))
340
341
result5 = validate_model(task_instance=self)
342
self.execution_log.append(('validate_model', result5))
343
344
result6 = deploy_model(task_instance=self)
345
self.execution_log.append(('deploy_model', result6))
346
347
self.end_time = datetime.now()
348
logger.info("Pipeline execution completed successfully")
349
350
except Exception as e:
351
logger.error(f"Pipeline execution failed: {str(e)}")
352
353
def xcom_push(self, key, value):
354
if not hasattr(self, 'xcom_storage'):
355
self.xcom_storage = {}
356
self.xcom_storage[key] = value
357
358
def xcom_pull(self, key, task_ids):
359
if hasattr(self, 'xcom_storage') and key in self.xcom_storage:
360
return self.xcom_storage[key]
361
return None
362
363
def get_summary(self):
364
duration = (self.end_time - self.start_time).total_seconds() if self.end_time else 0
365
return {
366
'start_time': self.start_time.isoformat() if self.start_time else None,
367
'end_time': self.end_time.isoformat() if self.end_time else None,
368
'duration_seconds': duration,
369
'tasks_executed': len(self.execution_log),
370
'execution_log': self.execution_log
371
}
372
373
# Execute pipeline
374
orchestrator = PipelineOrchestrator()
375
orchestrator.run_pipeline()
376
summary = orchestrator.get_summary()
377
378
print("\n=== Pipeline Summary ===")
379
for key, value in summary.items():
380
if key != 'execution_log':
381
print(f"{key}: {value}")
382
383
print("\nTask Execution Log:")
384
for task_name, result in summary['execution_log']:
385
print(f" {task_name}: {result}")
386
387
print("\nML pipeline automation setup completed!")
388
```
389
390
## Pipeline Best Practices
391
392
- **Modularity**: Each step should be independent
393
- **Idempotency**: Tasks should be safely repeatable
394
- **Error Handling**: Graceful degradation and alerting
395
- **Versioning**: Track data, code, and model versions
396
- **Monitoring**: Track execution metrics and logs
397
398
## Scheduling Strategies
399
400
- **Daily**: Standard for daily retraining
401
- **Weekly**: For larger feature engineering
402
- **On-demand**: Triggered by data updates
403
- **Real-time**: For streaming applications
404
405
## Deliverables
406
407
- Automated pipeline DAG
408
- Task dependency graph
409
- Execution logs and monitoring
410
- Performance metrics
411
- Rollback procedures
412
- Documentation
413