Creating a complete machine learning project that includes model development, REST API deployment with FastAPI, containerization with Docker, and setting up CI/CD pipelines using Jenkins and Docker on your local machine can seem daunting. However, by breaking it down into manageable steps, you can achieve a seamless workflow. Below is a comprehensive step-by-step tutorial to guide you through the entire process.
Table of Contents
- Prerequisites
- Step 1: Setting Up the Development Environment
- Step 2: Implementing the Iris Classification Model
- Step 3: Creating a REST API with FastAPI
- Step 4: Dockerizing the Application
- Step 5: Setting Up Jenkins and Docker
- Step 6: Creating CI/CD Pipelines with Jenkins
- Conclusion
Prerequisites
Before diving into the steps, ensure you have the following installed on your local machine:
Additionally, familiarity with Python, REST APIs, Docker, and basic Jenkins operations will be beneficial.
Step 1: Setting Up the Development Environment
1.1. Create a Project Directory
First, create a directory for your project and navigate into it.
mkdir iris-classification
cd iris-classification
1.2. Set Up a Virtual Environment
It's good practice to use a virtual environment to manage dependencies.
python -m venv venv
Activate the virtual environment:
-
Windows:
venv\Scripts\activate
-
macOS/Linux:
source venv/bin/activate
1.3. Install Required Python Packages
We'll need several libraries for data processing, model building, API development, and more.
pip install pandas scikit-learn fastapi uvicorn joblib matplotlib seaborn
Additionally, for development purposes, you might want to install pytest for testing:
pip install pytest
1.4. Initialize a Git Repository
Initialize Git to track your project.
git init
Create a .gitignore file to exclude unnecessary files.
touch .gitignore
Add the following to .gitignore:
venv/
__pycache__/
*.pyc
model.joblib
Step 2: Implementing the Iris Classification Model
In this step, we'll develop the Iris classification model, train it, and save it for later use in the API.
2.1. Create the Data Preparation and Model Training Script
Create a new Python script named train_model.py.
touch train_model.py
Open train_model.py in your code editor and add the following code:
# train_model.py
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
import joblib
def main():
# Load the Iris dataset
iris = load_iris()
data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
data['species'] = iris.target
species_mapping = {0: 'setosa', 1: 'versicolor', 2: 'virginica'}
data['species'] = data['species'].map(species_mapping)
# Features and target
X = data.drop('species', axis=1)
y = data['species']
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Model training
model = LogisticRegression(max_iter=200)
model.fit(X_train_scaled, y_train)
# Predictions
y_pred = model.predict(X_test_scaled)
# Evaluation
print("Classification Report:")
print(classification_report(y_test, y_pred))
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
# Save the model and scaler
joblib.dump(model, 'model.joblib')
joblib.dump(scaler, 'scaler.joblib')
print("Model and scaler saved.")
if __name__ == "__main__":
main()
2.2. Run the Training Script
Execute the training script to train the model and save it along with the scaler.
python train_model.py
You should see the classification report, confusion matrix, and confirmation that the model and scaler have been saved.
2.3. Review Saved Artifacts
After running the script, you should have two new files in your project directory:
model.joblib: The trained Logistic Regression model.
scaler.joblib: The fitted StandardScaler for feature scaling.
You can add these to your .gitignore if they're not already included.
Step 3: Creating a REST API with FastAPI
Now, we'll create a REST API that uses the trained model to predict iris species based on input features.
3.1. Create the FastAPI Application
Create a new Python script named main.py.
touch main.py
Open main.py in your editor and add the following code:
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import joblib
import numpy as np
app = FastAPI(title="Iris Classification API")
# Load the trained model and scaler
model = joblib.load('model.joblib')
scaler = joblib.load('scaler.joblib')
# Define the request body using Pydantic
class IrisRequest(BaseModel):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
class IrisResponse(BaseModel):
species: str
probabilities: dict
@app.post("/predict", response_model=IrisResponse)
def predict_species(iris: IrisRequest):
try:
# Create a numpy array from the input
features = np.array([
iris.sepal_length,
iris.sepal_width,
iris.petal_length,
iris.petal_width
]).reshape(1, -1)
# Scale features
scaled_features = scaler.transform(features)
# Predict probabilities
probabilities = model.predict_proba(scaled_features)[0]
# Get predicted class
predicted_class = model.predict(scaled_features)[0]
# Map class probabilities
class_probabilities = {
"setosa": round(probabilities[0], 4),
"versicolor": round(probabilities[1], 4),
"virginica": round(probabilities[2], 4)
}
return IrisResponse(species=predicted_class, probabilities=class_probabilities)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
3.2. Run the FastAPI Application
Use uvicorn to run the FastAPI application.
uvicorn main:app --reload
main: Refers to main.py
app: The FastAPI instance
--reload: Enables auto-reloading on code changes
You should see output indicating that the server is running, typically at http://127.0.0.1:8000.
3.3. Test the API
Open your browser and navigate to http://127.0.0.1:8000/docs to access the interactive Swagger UI documentation.
Click on the /predict endpoint, then "Try it out" to input sample data and execute a prediction.
Sample Input:
{
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}
Expected Output:
{
"species": "setosa",
"probabilities": {
"setosa": 1.0,
"versicolor": 0.0,
"virginica": 0.0
}
}
3.4. Add Basic Validation (Optional)
For production-grade APIs, consider adding more validation, error handling, and security measures. You can use FastAPI's dependency injection and middleware for enhanced functionalities.
Step 4: Dockerizing the Application
Containerizing your application ensures consistency across different environments and simplifies deployment.
4.1. Create a Dockerfile
In your project root, create a file named Dockerfile.
touch Dockerfile
Add the following content to the Dockerfile:
# Use an official Python runtime as the base image
FROM python:3.9-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
# Copy project
COPY . .
# Expose the port FastAPI is running on
EXPOSE 8000
# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
4.2. Create a requirements.txt File
To specify dependencies for Docker, create a requirements.txt file.
pip freeze > requirements.txt
Ensure that requirements.txt includes all necessary packages, such as:
fastapi==0.95.0
joblib==1.3.0
numpy==1.24.3
pandas==1.5.3
scikit-learn==1.2.2
uvicorn==0.22.0
matplotlib==3.7.2
seaborn==0.12.2
Note: The versions may vary based on your environment.
4.3. Update .gitignore
Ensure model.joblib and scaler.joblib are included in .gitignore to avoid committing model artifacts.
model.joblib
scaler.joblib
4.4. Build the Docker Image
Run the following command to build the Docker image. Make sure you're in the project directory containing the Dockerfile.
docker build -t iris-classification-api .
-t iris-classification-api: Tags the image with the name iris-classification-api.
4.5. Run the Docker Container
After successfully building the image, run the container.
docker run -d -p 8000:8000 --name iris_api_container iris-classification-api
-d: Runs the container in detached mode.
-p 8000:8000: Maps port 8000 of the host to port 8000 of the container.
--name iris_api_container: Names the container for easier management.
4.6. Test the Dockerized API
Navigate to http://localhost:8000/docs in your browser to access the Swagger UI for the API running inside the Docker container.
You should be able to perform predictions as before.
4.7. Stop and Remove the Container (Optional)
If you need to stop the container:
docker stop iris_api_container
To remove the container:
docker rm iris_api_container
Step 5: Setting Up Jenkins and Docker
To implement CI/CD pipelines, Jenkins will automate the build, test, and deployment processes.
5.1. Install Jenkins
If Jenkins is not already installed, follow these steps based on your operating system.
-
macOS with Homebrew:
brew install jenkins-lts
brew services start jenkins-lts
-
Windows:
Download the Jenkins Windows installer from Jenkins Downloads and follow the installation instructions.
-
Linux:
Follow the official Jenkins installation guide for your specific distribution.
5.2. Install Docker
Ensure Docker is installed and running on your machine. Refer to the Docker installation guide if you haven't installed it yet.
5.3. Configure Jenkins for Docker
-
Add Jenkins User to Docker Group:
To allow Jenkins to execute Docker commands, add the Jenkins user to the Docker group.
sudo usermod -aG docker jenkins
Then, restart Jenkins:
sudo systemctl restart jenkins
-
Install Docker Pipeline Plugin:
- Open Jenkins in your browser (typically at
http://localhost:8080).
- Navigate to Manage Jenkins > Manage Plugins.
- In the Available tab, search for
Docker Pipeline.
- Install the plugin and restart Jenkins if prompted.
5.4. Secure Jenkins
For security, ensure Jenkins is secured by configuring users, credentials, and permissions. Refer to the Jenkins security guide for detailed instructions.
Step 6: Creating CI/CD Pipelines with Jenkins
Now, we'll set up Jenkins to automate the build, test, and deployment of our Iris classification API.
6.1. Prepare Your Project Repository
To enable Jenkins to access your project, host your code in a version control system like Git. For local development, you can initialize a Git repository.
git remote add origin <your-repo-url>
git add .
git commit -m "Initial commit"
git push -u origin master
Note: Replace <your-repo-url> with your actual repository URL, e.g., GitHub, GitLab.
6.2. Create a Jenkins Pipeline Job
-
Access Jenkins Dashboard:
- Open Jenkins in your browser (
http://localhost:8080).
-
Create a New Job:
- Click on New Item.
- Enter a name, e.g.,
Iris-Classification-CI_CD.
- Select Pipeline and click OK.
-
Configure the Pipeline:
-
General Tab:
- Optionally, add a description.
-
Pipeline Tab:
- Definition: Choose Pipeline script from SCM.
- SCM: Select Git.
- Repository URL: Enter your Git repository URL.
- Credentials: Add if required.
- Branch: Specify the branch to build, typically
master or main.
- Script Path: If your
Jenkinsfile is in the root, leave it as Jenkinsfile.
-
Save the Job:
Click Save to store the pipeline configuration.
6.3. Create a Jenkinsfile
Create a Jenkinsfile in your project root to define the CI/CD pipeline stages.
touch Jenkinsfile
Open Jenkinsfile in your editor and add the following content:
pipeline {
agent any
environment {
IMAGE_NAME = "iris-classification-api"
CONTAINER_NAME = "iris_api_container"
}
stages {
stage('Checkout') {
steps {
// Checkout the Git repository
git branch: 'master', url: 'https://github.com/your-username/iris-classification.git'
}
}
stage('Set Up Python Environment') {
steps {
// Set up virtual environment and install dependencies
sh 'python3 -m venv venv'
sh '. venv/bin/activate && pip install --upgrade pip'
sh '. venv/bin/activate && pip install -r requirements.txt'
}
}
stage('Run Tests') {
steps {
// Run pytest (Implement tests as needed)
sh '. venv/bin/activate && pytest'
}
}
stage('Build Docker Image') {
steps {
// Build Docker image
sh 'docker build -t $IMAGE_NAME .'
}
}
stage('Deploy') {
steps {
// Stop and remove existing container if exists
sh '''
if [ "$(docker ps -a | grep $CONTAINER_NAME)" ]; then
docker stop $CONTAINER_NAME
docker rm $CONTAINER_NAME
fi
'''
// Run the new Docker container
sh 'docker run -d -p 8000:8000 --name $CONTAINER_NAME $IMAGE_NAME'
}
}
}
post {
success {
echo 'Pipeline completed successfully!'
}
failure {
echo 'Pipeline failed.'
}
}
}
Explanation of the Jenkinsfile:
-
Stages:
- Checkout: Clones the Git repository.
- Set Up Python Environment: Sets up a virtual environment and installs dependencies.
- Run Tests: Executes tests using
pytest. (Ensure you have tests implemented.)
- Build Docker Image: Builds the Docker image using the
Dockerfile.
- Deploy: Stops and removes any existing container with the same name and runs a new container.
-
Environment Variables:
IMAGE_NAME: Name of the Docker image.
CONTAINER_NAME: Name of the Docker container.
-
Post Actions:
- Logs messages based on pipeline success or failure.
6.4. Implement Tests (Optional but Recommended)
Implement tests to ensure your model and API are functioning correctly.
Create a test_api.py file:
touch test_api.py
Add the following sample test using pytest and requests:
# test_api.py
import requests
def test_predict_setosa():
url = "http://localhost:8000/predict"
payload = {
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}
response = requests.post(url, json=payload)
assert response.status_code == 200
data = response.json()
assert data['species'] == 'setosa'
assert data['probabilities']['setosa'] == 1.0
Note: For Jenkins to run these tests, the API should be running during the test stage or use a testing strategy like starting the API in a test environment.
6.5. Trigger the Pipeline
-
Start the Pipeline:
- In the Jenkins dashboard, navigate to your pipeline job (e.g.,
Iris-Classification-CI_CD).
- Click Build Now.
-
Monitor the Pipeline:
- Click on the build number to see the build progress and logs.
- Ensure all stages complete successfully.
-
Verify Deployment:
- After deployment, verify the API is accessible at
http://localhost:8000/docs.
Additional Enhancements
7.1. Automate Model Training
For a more robust CI/CD pipeline, consider:
-
Automating Model Retraining: If your model needs periodic retraining based on new data, include steps in the pipeline to retrain and redeploy the model.
-
Versioning Models: Use a model registry to manage different versions of your model for better tracking and rollback capabilities.
7.2. Integrate Testing into Docker Build
Implement tests within the Docker build process to ensure the container is built correctly.
7.3. Use Docker Compose
For more complex deployments involving multiple services, consider using Docker Compose to manage multi-container applications.
7.4. Implement Clean-up Strategies
Ensure that old Docker images and containers are cleaned up to save disk space and maintain performance.
Conclusion
By following this comprehensive guide, you've successfully:
- Developed and trained an Iris classification model using Python and scikit-learn.
- Created a FastAPI-based REST API to serve the model predictions.
- Containerized the application using Docker for consistent deployment.
- Set up Jenkins and Docker on your local machine.
- Created a CI/CD pipeline in Jenkins to automate building, testing, and deploying your application.
This setup provides a solid foundation for developing and deploying machine learning models with automated workflows. You can further enhance the pipeline by integrating additional testing, monitoring, and scaling strategies as your project evolves.
Resources:
Feel free to reach out if you encounter any issues or have further questions. Happy coding!