Skip to content

Commit

Permalink
deploy the ml model to flask
Browse files Browse the repository at this point in the history
  • Loading branch information
adiglase committed Jun 14, 2023
1 parent 5f1fd3e commit 29f4ca7
Show file tree
Hide file tree
Showing 18 changed files with 108 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FLASK_APP=project/app.py
FLASK_DEBUG=1
FLASK_RUN_PORT=8002
3 changes: 3 additions & 0 deletions .env.prod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FLASK_APP=project/app.py
FLASK_DEBUG=0
FLASK_RUN_PORT=8002
11 changes: 11 additions & 0 deletions Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.10-slim-buster

ENV PYTHONUNBUFFERED=1

WORKDIR /carbonzero-ml-model-dir

COPY ./carbonzero_ml_model/requirements.txt ./requirements.txt
COPY ./carbonzero_ml_model/.env.dev ./.env.dev
RUN pip3 install -r requirements.txt

COPY ./carbonzero_ml_model/. .
11 changes: 11 additions & 0 deletions Dockerfile.prod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.10-slim-buster

ENV PYTHONUNBUFFERED=1

WORKDIR /carbonzero-ml-model-dir

COPY ./carbonzero_ml_model/requirements.txt ./requirements.txt
COPY ./carbonzero_ml_model/.env.prod ./.env.prod
RUN pip3 install -r requirements.txt

COPY ./carbonzero_ml_model/. .
Binary file added __pycache__/app.cpython-38.pyc
Binary file not shown.
Empty file added entrypoint.sh
Empty file.
8 changes: 8 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from flask.cli import FlaskGroup
from project.app import app

cli = FlaskGroup(app)

if __name__ == "__main__":
cli()

Binary file added model.pkl
Binary file not shown.
Empty file added project/__init__.py
Empty file.
Binary file added project/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added project/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added project/__pycache__/app.cpython-310.pyc
Binary file not shown.
Binary file added project/__pycache__/app.cpython-38.pyc
Binary file not shown.
Binary file added project/__pycache__/model.cpython-310.pyc
Binary file not shown.
29 changes: 29 additions & 0 deletions project/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from flask import Flask, jsonify, Blueprint, request
from flask_restx import Api, Resource, fields, fields, abort
from .model import model
import numpy as np

app_ins = Flask(__name__)

blueprint = Blueprint('api', __name__, url_prefix='/api/ml-model')
app = Api(blueprint, default="API", default_label="ML Model API")

app_ins.register_blueprint(blueprint)

carbon_emission_fields = app.model('Total Emission', {
'total_emission': fields.Integer,
})
@app.route("/carbon_emission_comparison")
class MyResource(Resource):
@app.expect(carbon_emission_fields, validate=True)
def post(self):
try:
total_emission = float(request.json['total_emission'])
prediction = model.predict(np.array([[total_emission]]))

predicted_class = prediction.argmax()
return jsonify(result=int(predicted_class))
except ValueError:
abort(400, "Invalid total_emission value")
except Exception as e:
abort(400, str(e))
File renamed without changes.
36 changes: 36 additions & 0 deletions project/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import tensorflow as tf # for model arc
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
import pandas as pd # for split dataset
from sklearn.model_selection import train_test_split
import numpy as np # for predict or test the model
import pickle
import os

dataset = pd.read_csv('project/datasetKgCO2.csv', delimiter=',', header=0)

x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values

# Split dataset into train and validation
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=0)

# Model architecture
model = Sequential([
Dense(64, activation='relu', input_shape=(None, 1)),
Dense(32, activation='relu'),
LSTM(4, activation='relu'),
Dense(32, activation='relu'),
Dense(4, activation='linear')])

# Optimizer and loss for the model
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['acc'])

# Training the model
model.fit(tf.expand_dims(x_train, axis=-1), y_train, epochs=100, validation_data=(x_val, y_val), steps_per_epoch=10)

pickle.dump(model, open('model.pkl', 'wb'))

model = pickle.load(open('model.pkl', 'rb'))
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Flask==2.3.2
gunicorn==20.1.0
flask-restx==1.1.0
tensorflow==2.12.0
numpy==1.23.5
pandas==2.0.2
scikit-learn==1.2.2

0 comments on commit 29f4ca7

Please sign in to comment.