0% found this document useful (0 votes)
4 views8 pages

Assignment - 4

This document outlines the steps to build, train, containerize, and deploy a machine learning model using Flask, Docker, and Kubernetes. It includes details on creating the model, setting up the Flask application, building a Docker image, and deploying the application with Kubernetes manifests. The document provides code snippets and commands necessary for each step of the process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Assignment - 4

This document outlines the steps to build, train, containerize, and deploy a machine learning model using Flask, Docker, and Kubernetes. It includes details on creating the model, setting up the Flask application, building a Docker image, and deploying the application with Kubernetes manifests. The document provides code snippets and commands necessary for each step of the process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Nisarga H N CAN_ID: CAN_33243664

Cauvery Institute of Technology, Mandya

ASSIGNMENT – 3: Building and Training a Machine Learning Model,


Containerizing, and Deploying a Machine Learning Model Using Flask, Docker
Images, and Kubernetes Services

Step 1: Create the ML Model

Directory structure:

ml-app/

├── app/

│ ├── model.py

│ ├── app.py

│ └── requirements.txt

├── Dockerfile

├── kubernetes/

│ ├── deployment.yaml

│ └── service.yaml

└── README.md
Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

2. ML model code (model.py):


import pickle
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

# Train and save a model


def train_model ():
try:
# Load dataset
data = load_iris ()
X, y = data.data, data.target

# Train a simple model


model = RandomForestClassifier ()
model.fit(X, y)

# Save the model to a file


with open ("model.pkl", "wb") as file:
pickle.dump(model, file)
print ("Model created and saved as 'model.pkl'")
except Exception as e:
print (f"Error: {e}")

if __name__ == "__main__":
train_model ()

3. Flask app code (app.py):


import pickle
from flask import Flask, request, jsonify
app = Flask(__name__)
Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

# Load the trained model


with open("model.pkl", "rb") as file:
model = pickle.load(file)
@app.route("/")
def home():
return "Welcome to the ML App!"
@app.route("/predict", methods=["POST"])
def predict():
data = request.json
prediction = model.predict([data["features"]])
return jsonify({"prediction": prediction.tolist()})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)

4. Requirements file (requirements.txt):


Flask==2.3.3
scikit-learn==1.3.2
5. Train the model:
Run the model.py script to generate the model.pkl file:

python app/model.py
Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

Step 2: Create a Docker Image


1.Dockerfile:
FROM python:3.9-slim
WORKDIR /app
# Copy the application and the model file into the Docker image COPY app/ /app/
COPY model.pkl /app/
RUN pip install -r requirements.txt EXPOSE 5000
CMD ["python", "app.py"]

Step 3: Verify Image Availability

Ensure Kubernetes can access the image:

docker images

1. Build the Docker image:

docker build -t ml-app .


Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

2. Test the Docker container locally:

docker run -p 5000:5000 ml-app

If you’re using a remote image, ensure it is pushed to a container registry like


Docker Hub:
docker tag ml-app:latest nisargahn2004/ml-app:latest

docker push nisargahn2004/ml-app:latest


Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

Step 3: Deploy with Minikube and kubectl

1. Start Minikube:
minikube start

2.Create Kubernetes manifests:


o Deployment (deployment.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-app
spec:
replicas: 1
selector:
matchLabels:
app: ml-app
Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

template:
metadata:
labels:
app: ml-app
spec:
containers:
- name: ml-app
image: nisargahn2004/ml-app:latest
ports:
- containerPort: 5000

o Service (service.yaml):
apiVersion: v1
kind: Service
metadata:
name: ml-app-service
spec:
selector:
app: ml-app
ports:
- protocol: TCP
port: 80
targetPort: 5000
type: NodePort

1. Apply the manifests:

kubectl apply -f kubernetes/deployment.yaml

kubectl apply -f kubernetes/service.yaml


Nisarga H N CAN_ID: CAN_33243664
Cauvery Institute of Technology, Mandya

Check Deployment and Service


1. Check Deployment: Verify the status of the Deployment:

kubectl get deployments


kubectl get pods
kubectl get svc

4. Access the service: Get the service URL using Minikube:

minikube service ml-app-service

You might also like