Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as Python by Lutfi ( 6 years ago )
import flask
from flask import Flask, request, jsonify, render_template
from flask_restful import reqparse, abort, Api, Resource
import joblib
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import OneHotEncoder, LabelBinarizer, StandardScaler, LabelEncoder
from sklearn_pandas import DataFrameMapper
import os
import time
from time import gmtime, strftime
import json
import traceback

print(time.tzname)

#Initialize the flask App
app = Flask(__name__)

#Mestinya disini ada inisiasi api
api = Api(app)

model = joblib.load('model/best_model.pkl', 'r')
mapper_fit = joblib.load('model/mapper_fit.pkl', 'r')

numerical_cols = ['sub_grade_num', 'short_emp', 'emp_length_num','dti', 'payment_inc_ratio', 'delinq_2yrs', \
                'delinq_2yrs_zero', 'inq_last_6mths', 'last_delinq_none', 'last_major_derog_none', 'open_acc',\
                'pub_rec', 'pub_rec_zero','revol_util']

categorical_cols=['grade', 'home_ownership', 'purpose']

# Yang dipakai untuk pasang route kalau untuk API
# Contoh pemasangan decoratornya
# pakai api.route("/api/predict") , kalau misal untuk web pakai app.route("/")
@app.route('/')
def welcome():
    return str("Credit Scoring Prediction")

@app.route('/predict', methods=['POST','GET'])
def predict():
    if flask.request.method == 'GET':
        return str("Prediction page")

    if flask.request.method == 'POST':
        try:
            json_data = request.json
            dfx = pd.DataFrame(json_data,index=[0])
            print(dfx)
            XX1 = mapper_fit.transform(dfx)
            XX2 = dfx[numerical_cols]
            XX = np.hstack((XX1,XX2))

            prediction = model.predict(XX)
            prediction_good_loan = model.predict_proba(XX)[:,0][0]
            prediction_bad_loan = model.predict_proba(XX)[:,1][0]

            if int(prediction) == 1:
                prediction_result = str("Bad Loan")
            else:
                prediction_result = str("Good Loan")

            if int(prediction) == 1:
                prob_result = str(round(prediction_bad_loan*100,1))+"%"
            else:
                prob_result = str(round(prediction_good_loan*100,1))+"%"

            return jsonify({
                "prediction":str(prediction_result),
                "prob":str(prob_result)
            })
 
        except:
            return jsonify({
                "trace": traceback.format_exc()
            })
    else:
        print ('Train the model first')
        return ('No model here to use')

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

 

Revise this Paste

Parent: 108331
Your Name: Code Language: