Skip to content

Commit

Permalink
Update serve_model.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel-Andarge authored Jun 30, 2024
1 parent e5c7bdb commit c2b059e
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions flask-app/serve_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from flask import Flask, request, jsonify
import pandas as pd
from lime import lime_tabular
import shap
import lime
import pickle
import os
import sys
Expand All @@ -17,6 +20,7 @@
def home():
return ("Welcome to ML based fraud detction")


@app.route('/predict', methods=['POST'])
def detect():
try:
Expand All @@ -27,21 +31,29 @@ def detect():
df['signup_time'] = pd.to_datetime(df['signup_time'])
df['purchase_time'] = pd.to_datetime(df['purchase_time'])

# FeatureEngineering
# Feature Engineering
fg = FeatureEngineering(df)
featured_df = fg.preprocess()
if len(featured_df) > 0:
# Make detection
result = model.predict(featured_df.values).tolist()
detection_results = ["Fraud" if res == 1 else "Not Fraud" for res in result]
return jsonify({'Detection': detection_results})

# SHAP Explanation
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(featured_df)
shap_summary = shap.summary_plot(shap_values, featured_df, plot_type="bar")

# LIME Explanation
lime_explainer = lime_tabular.LimeTabularExplainer(featured_df.values, feature_names=featured_df.columns)
lime_exp = lime_explainer.explain_instance(featured_df.iloc[0].values, model.predict_proba, num_features=5)
lime_explanation = lime_exp.as_html()

return jsonify({'Detection': detection_results, 'SHAP_Explanation': shap_summary, 'LIME_Explanation': lime_explanation})
else:
return jsonify({'error': 'No data provided for detection'}), 400

except KeyError as ke:
return jsonify({'error': f"Missing key in the input data: {ke}"}), 400
except Exception as e:
return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
app.run(debug=True)

0 comments on commit c2b059e

Please sign in to comment.