Converting your Jupyter notebook into a well-structured Python module (preprocessing.py) is a crucial step toward building a scalable, maintainable, and production-ready MLOps project. Below, I outline a comprehensive approach to transforming your preprocessing steps into a Python module, integrating best practices such as clean code, modularity, error handling, exception management, and data validation. Additionally, I provide guidance on how this module fits into your overall project structure.
1. Project Structure Overview
Given your initial folder structure and the feedback provided, here's an enhanced version that accommodates robust preprocessing:
MLOPS-TELCO-CHURN/
├── app/
│ ├── api/
│ └── services/
│ ├── __init__.py
│ ├── feature_engineering.py
│ ├── load_data.py
│ ├── model_training.py
│ └── preprocessing.py
├── tests/
│ ├── api/
│ └── services/
│ ├── test_preprocessing.py
│ └── ...
├── utils/
│ ├── __init__.py
│ ├── config.py
│ └── logger.py
├── config/
│ ├── config.yaml
│ └── params.yaml
├── data/
│ ├── raw/
│ │ └── data.csv
│ └── processed/
├── models/
│ └── model_v1.pkl
├── pipelines/
│ ├── data_pipeline.py
│ └── training_pipeline.py
├── notebooks/
│ └── exploratory_analysis.ipynb
├── docs/
│ └── api_documentation.md
├── scripts/
│ ├── train.sh
│ └── deploy.sh
├── Dockerfile
├── docker-compose.yml
├── .env
├── .gitignore
├── README.md
├── LICENSE
├── main.py
└── requirements.txt
Key Enhancements:
requirements.txt: Define all project dependencies for reproducibility.
tests/services/test_preprocessing.py: Unit tests for your preprocessing module.
notebooks/: Contains Jupyter notebooks for exploratory data analysis (kept separate from production code).
data/processed/: Stores preprocessed data outputs.
pipelines/: Manages data and training pipelines for automation.
docs/: Detailed project documentation.
scripts/: Scripts for training, deployment, and other automation tasks.
2. Creating preprocessing.py with Best Practices
a. Module Overview
The preprocessing.py module should encapsulate all preprocessing steps, making it reusable and maintainable. It should:
- Load Data: Read raw data from the specified location.
- Handle Categorical Encoding: Apply
LabelEncoder or other encoding techniques.
- Scale Numerical Features: Standardize or normalize numerical data.
- Split Data: Divide data into training and testing sets.
- Save Preprocessed Data: Store the processed data for downstream tasks.
- Logging and Configuration: Utilize centralized logging and configuration management.
- Error Handling: Gracefully handle potential errors during preprocessing.
b. Implementing preprocessing.py
Below is an example implementation of preprocessing.py adhering to the best practices:
# app/services/preprocessing.py
import os
import logging
import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from utils.config import Config
from utils.logger import get_logger
class Preprocessor:
def __init__(self, config_path: str):
self.config = Config(config_path)
self.logger = get_logger(__name__)
self.label_encoders = {}
self.scaler = StandardScaler()
def load_data(self) -> pd.DataFrame:
data_path = self.config.get('data.raw_data_path')
try:
self.logger.info(f"Loading data from {data_path}")
data = pd.read_csv(data_path)
self.logger.info("Data loaded successfully")
return data
except FileNotFoundError as e:
self.logger.error(f"File not found: {data_path}")
raise e
except pd.errors.ParserError as e:
self.logger.error(f"Error parsing CSV: {e}")
raise e
def object_to_int(self, dataframe_series: pd.Series) -> pd.Series:
if dataframe_series.dtype == 'object':
encoder = LabelEncoder()
try:
self.logger.debug(f"Encoding column: {dataframe_series.name}")
encoded = encoder.fit_transform(dataframe_series)
self.label_encoders[dataframe_series.name] = encoder
return encoded
except Exception as e:
self.logger.error(f"Error encoding column {dataframe_series.name}: {e}")
raise e
return dataframe_series
def encode_categorical_columns(self, df: pd.DataFrame, categorical_cols: list) -> pd.DataFrame:
self.logger.info("Starting categorical encoding")
for col in categorical_cols:
df[col] = self.object_to_int(df[col])
self.logger.info("Categorical encoding completed")
return df
def scale_numerical_columns(self, df: pd.DataFrame, numerical_cols: list) -> pd.DataFrame:
self.logger.info("Starting numerical scaling")
try:
df[numerical_cols] = self.scaler.fit_transform(df[numerical_cols])
self.logger.info("Numerical scaling completed")
return df
except Exception as e:
self.logger.error(f"Error scaling numerical columns: {e}")
raise e
def split_data(self, df: pd.DataFrame, target: str, test_size: float, random_state: int):
self.logger.info("Starting data split")
try:
X = df.drop(columns=[target])
y = df[target].values
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=test_size,
random_state=random_state,
stratify=y
)
self.logger.info("Data split completed")
return X_train, X_test, y_train, y_test
except Exception as e:
self.logger.error(f"Error splitting data: {e}")
raise e
def save_preprocessed_data(self, X_train, X_test, y_train, y_test):
processed_dir = self.config.get('data.processed_data_dir')
os.makedirs(processed_dir, exist_ok=True)
try:
self.logger.info("Saving preprocessed data")
pd.DataFrame(X_train).to_csv(os.path.join(processed_dir, 'X_train.csv'), index=False)
pd.DataFrame(X_test).to_csv(os.path.join(processed_dir, 'X_test.csv'), index=False)
pd.DataFrame(y_train, columns=['Churn']).to_csv(os.path.join(processed_dir, 'y_train.csv'), index=False)
pd.DataFrame(y_test, columns=['Churn']).to_csv(os.path.join(processed_dir, 'y_test.csv'), index=False)
self.logger.info("Preprocessed data saved successfully")
except Exception as e:
self.logger.error(f"Error saving preprocessed data: {e}")
raise e
def preprocess(self):
df = self.load_data()
# Define columns
numerical_cols = self.config.get('preprocessing.numerical_cols')
categorical_cols_ohe = self.config.get('preprocessing.categorical_cols_ohe')
categorical_cols_le = self.config.get('preprocessing.categorical_cols_le')
target = self.config.get('preprocessing.target')
test_size = self.config.get('preprocessing.test_size')
random_state = self.config.get('preprocessing.random_state')
# Encode categorical columns
df = self.encode_categorical_columns(df, categorical_cols_le)
# Scale numerical columns
df = self.scale_numerical_columns(df, numerical_cols)
# Split data
X_train, X_test, y_train, y_test = self.split_data(df, target, test_size, random_state)
# Save preprocessed data
self.save_preprocessed_data(X_train, X_test, y_train, y_test)
self.logger.info("Preprocessing pipeline completed successfully")
if __name__ == "__main__":
preprocessor = Preprocessor(config_path="config/config.yaml")
preprocessor.preprocess()
c. Explanation of preprocessing.py Components
-
Imports and Dependencies:
- Standard Libraries:
os, logging for file operations and logging.
- Third-Party Libraries:
pandas, sklearn for data manipulation and preprocessing.
- Project Utilities:
Config and get_logger from utils.
-
Preprocessor Class:
- Initialization (
__init__):
- Loads configuration using a
Config class.
- Initializes a logger for logging events.
- Prepares dictionaries to store label encoders and the scaler.
-
Data Loading (load_data):
- Reads raw data from the path specified in the configuration.
- Includes error handling for file not found and parsing errors.
- Logs each step for traceability.
-
Categorical Encoding (object_to_int and encode_categorical_columns):
object_to_int: Encodes a single categorical column using LabelEncoder.
encode_categorical_columns: Iterates over specified categorical columns and applies encoding.
-
Numerical Scaling (scale_numerical_columns):
- Applies
StandardScaler to numerical columns.
- Includes error handling and logging.
-
Data Splitting (split_data):
- Splits the dataset into training and testing sets.
- Uses stratification based on the target variable to maintain class distribution.
-
Saving Preprocessed Data (save_preprocessed_data):
- Saves the processed datasets to the
data/processed/ directory.
- Ensures the directory exists and handles potential errors during saving.
-
Preprocessing Pipeline (preprocess):
- Orchestrates the entire preprocessing workflow by calling the above methods in sequence.
d. Supporting Modules
i. Configuration Management (config.py)
Using a configuration file (e.g., config.yaml) allows for flexible parameter management without hardcoding values.
# utils/config.py
import yaml
import os
class Config:
def __init__(self, config_path: str):
self.config = self.load_config(config_path)
def load_config(self, path: str) -> dict:
if not os.path.exists(path):
raise FileNotFoundError(f"Configuration file not found at path: {path}")
with open(path, 'r') as file:
return yaml.safe_load(file)
def get(self, key: str):
keys = key.split('.')
value = self.config
for k in keys:
value = value.get(k)
if value is None:
raise KeyError(f"Configuration key '{key}' not found.")
return value
Example config.yaml:
data:
raw_data_path: data/raw/data.csv
processed_data_dir: data/processed/
preprocessing:
numerical_cols:
- tenure
- MonthlyCharges
- TotalCharges
categorical_cols_ohe:
- PaymentMethod
- Contract
- InternetService
categorical_cols_le:
- Gender
- Partner
- Dependents
- PhoneService
- MultipleLines
- ...
target: Churn
test_size: 0.3
random_state: 40
ii. Logging Utility (logger.py)
Centralized logging ensures consistent and configurable logging across modules.
# utils/logger.py
import logging
import os
from logging.handlers import RotatingFileHandler
def get_logger(name: str) -> logging.Logger:
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# Prevent adding multiple handlers in interactive environments
if not logger.handlers:
# Create handlers
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
file_handler = RotatingFileHandler('logs/app.log', maxBytes=1000000, backupCount=3)
file_handler.setLevel(logging.DEBUG)
# Create formatters and add them to handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# Add handlers to the logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
Additional Steps:
- Create Logs Directory: Ensure a
logs/ directory exists or adjust the logging path accordingly.
- Logging Levels: Use appropriate logging levels (
DEBUG, INFO, WARNING, ERROR, CRITICAL) based on the message importance.
e. Error Handling and Data Validation
Throughout preprocessing.py, errors are caught and logged appropriately. Key practices include:
- Try-Except Blocks: Wrap potentially error-prone operations in
try-except blocks.
- Logging Errors: Log errors with clear messages to facilitate debugging.
- Raising Exceptions: Re-raise exceptions after logging to allow upstream handlers to manage them if necessary.
- Configuration Validation: Ensure all required configuration keys are present and valid.
f. Data Validation
Before processing, it's prudent to perform data validation to ensure data integrity.
Example Data Validation:
def validate_data(df: pd.DataFrame):
required_columns = ['tenure', 'MonthlyCharges', 'TotalCharges', 'Churn']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
raise ValueError(f"Missing required columns: {missing_columns}")
# Check for duplicates
if df.duplicated().any():
df.drop_duplicates(inplace=True)
preprocessor.logger.warning("Duplicates found and removed.")
# Check for missing values
if df.isnull().sum().any():
df.fillna(method='ffill', inplace=True)
preprocessor.logger.warning("Missing values found and filled.")
Integrate Validation into Pipeline:
Add a call to validate_data(df) after loading the data:
def preprocess(self):
df = self.load_data()
self.validate_data(df)
# ... rest of the preprocessing steps
3. Integrating preprocessing.py into the Project
a. Configuration File
Ensure your config/config.yaml is properly set up with all necessary parameters, as shown earlier.
b. Logging Setup
Create a logs/ directory to store log files or update the logger.py to handle dynamic paths.
c. Running the Preprocessing Module
You can execute the preprocessing module directly or integrate it into a pipeline.
Direct Execution:
python app/services/preprocessing.py
Integration into a Pipeline (e.g., main.py):
# main.py
from app.services.preprocessing import Preprocessor
def main():
preprocessor = Preprocessor(config_path="config/config.yaml")
try:
preprocessor.preprocess()
except Exception as e:
print(f"Preprocessing failed: {e}")
if __name__ == "__main__":
main()
Run via Main Script:
python main.py
d. Unit Testing (test_preprocessing.py)
Ensure your preprocessing functions work as expected.
# tests/services/test_preprocessing.py
import unittest
import pandas as pd
from app.services.preprocessing import Preprocessor
class TestPreprocessor(unittest.TestCase):
def setUp(self):
self.preprocessor = Preprocessor(config_path="config/config.yaml")
# Create a sample dataframe
data = {
'ID': [1, 2, 3, 4, 5],
'Color': ['Red', 'Blue', 'Green', 'Blue', 'Red'],
'Size': ['M', 'L', 'S', 'M', 'XL'],
'Shape': ['Circle', 'Square', 'Triangle', 'Circle', 'Square'],
'Price': [10.99, 12.50, 9.99, 11.50, 13.00],
'Availability': ['In Stock', 'Out of Stock', 'In Stock', 'In Stock', 'Out of Stock'],
'Churn': [0, 1, 0, 0, 1]
}
self.sample_df = pd.DataFrame(data)
def test_load_data_file_not_found(self):
with self.assertRaises(FileNotFoundError):
self.preprocessor.load_data()
def test_encode_categorical_columns(self):
categorical_cols_le = ['Color', 'Size', 'Shape', 'Availability']
self.preprocessor.encode_categorical_columns(self.sample_df, categorical_cols_le)
self.assertTrue(all(self.sample_df.dtypes[col] in [int, 'int64'] for col in categorical_cols_le))
def test_scale_numerical_columns(self):
numerical_cols = ['Price']
scaled_df = self.preprocessor.scale_numerical_columns(self.sample_df, numerical_cols)
self.assertAlmostEqual(scaled_df['Price'].mean(), 0, places=1)
self.assertAlmostEqual(scaled_df['Price'].std(), 1, places=1)
def test_split_data(self):
X_train, X_test, y_train, y_test = self.preprocessor.split_data(self.sample_df, 'Churn', 0.3, 40)
self.assertEqual(len(X_train) + len(X_test), len(self.sample_df))
self.assertEqual(len(y_train) + len(y_test), len(self.sample_df))
# Add more tests as needed
if __name__ == "__main__":
unittest.main()
Running Tests:
python -m unittest discover tests/
e. Dependency Management (requirements.txt)
List all dependencies to ensure reproducibility.
# requirements.txt
pandas==1.5.3
scikit-learn==1.2.2
PyYAML==6.0
Install Dependencies:
pip install -r requirements.txt
f. Version Control (.gitignore)
Ensure sensitive files and unnecessary directories are excluded from version control.
Example .gitignore:
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
*.egg-info/
dist/
build/
# Data files
data/raw/
data/processed/
logs/
*.csv
# Jupyter Notebooks
.ipynb_checkpoints
# Environment variables
.env
# IDEs and editors
.vscode/
.idea/
*.sublime-project
*.sublime-workspace
# Pytest cache
.pytest_cache/
4. Additional Best Practices
a. Modularity and Reusability
- Single Responsibility Principle: Each function/method should have a single responsibility.
- Reusability: Design functions that can be reused across different modules or projects.
b. Documentation
- Docstrings: Provide clear docstrings for classes and methods.
def load_data(self) -> pd.DataFrame:
"""
Loads raw data from the specified CSV file.
Returns:
pd.DataFrame: Loaded dataframe.
Raises:
FileNotFoundError: If the data file does not exist.
pd.errors.ParserError: If there's an error parsing the CSV.
"""
# Method implementation
- README.md: Include comprehensive instructions on setting up and running the project.
c. Configuration Management
- Environment Variables: Use
.env for sensitive information and environment-specific settings.
- Dynamic Configurations: Allow configurations to change based on environments (development, testing, production).
d. Logging Levels and Formats
- Consistent Logging: Use consistent formats and levels across all modules.
- Log Rotation: Implement log rotation to manage log file sizes.
e. Exception Handling Strategy
- Custom Exceptions: Define custom exception classes for more granular error handling.
- Graceful Degradation: Ensure the system can handle failures gracefully without crashing.
f. Testing
- Comprehensive Tests: Cover various scenarios, including edge cases.
- Continuous Testing: Integrate testing into CI/CD pipelines to ensure code quality.
g. Version Control for Data and Models
- Data Versioning: Use tools like DVC or Git LFS for managing large or changing datasets.
- Model Versioning: Track different versions of models using MLflow or similar tools.
h. Containerization and Deployment
- Docker: Containerize the application for consistent environments across development and production.
- Orchestration: Use Docker Compose or Kubernetes for managing multi-container applications.
i. Continuous Integration/Continuous Deployment (CI/CD)
- Automation: Automate testing, building, and deployment processes.
- Tools: Utilize GitHub Actions, GitLab CI, Jenkins, or similar tools for CI/CD workflows.
5. Final Thoughts
By meticulously structuring your project and encapsulating preprocessing steps within a dedicated, robust Python module, you ensure that your MLOps pipeline is scalable, maintainable, and aligned with industry best practices. This setup facilitates collaboration, eases debugging, and streamlines the deployment process, ultimately leading to more efficient and reliable machine learning workflows.
Next Steps:
-
Implement the Preprocessor Class:
- Populate the
preprocessing.py with all required preprocessing steps.
- Ensure all configurations are correctly specified in
config.yaml.
-
Develop Unit Tests:
- Create comprehensive tests in
test_preprocessing.py to validate each preprocessing function.
-
Set Up CI/CD Pipelines:
- Configure automated pipelines to run tests and deploy preprocessing as part of the ML workflow.
-
Document the Workflow:
- Update
README.md and other documentation to reflect the project structure and usage instructions.
-
Iterate and Improve:
- Continuously refine the preprocessing steps based on model performance and data insights.
By following these guidelines, you'll transform your preprocessing workflow into a robust, production-ready module that integrates seamlessly within your MLOps-Telco-Churn project.