|
|
from flask import Flask, request, jsonify
|
|
|
import joblib
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
model = joblib.load('random_forest_model.pkl')
|
|
|
|
|
|
@app.route('/')
|
|
|
def home():
|
|
|
return "Welcome to the Customer Churn Prediction API!"
|
|
|
|
|
|
|
|
|
@app.route('/predict', methods=['POST'])
|
|
|
def predict():
|
|
|
try:
|
|
|
|
|
|
data = request.get_json()
|
|
|
|
|
|
|
|
|
features = [
|
|
|
data.get("gender"),
|
|
|
data.get("SeniorCitizen"),
|
|
|
data.get("Partner"),
|
|
|
data.get("Dependents"),
|
|
|
data.get("tenure"),
|
|
|
data.get("PhoneService"),
|
|
|
data.get("MultipleLines"),
|
|
|
data.get("InternetService"),
|
|
|
data.get("OnlineSecurity"),
|
|
|
data.get("OnlineBackup"),
|
|
|
data.get("DeviceProtection"),
|
|
|
data.get("TechSupport"),
|
|
|
data.get("StreamingTV"),
|
|
|
data.get("StreamingMovies"),
|
|
|
data.get("Contract"),
|
|
|
data.get("PaperlessBilling"),
|
|
|
data.get("PaymentMethod"),
|
|
|
data.get("MonthlyCharges"),
|
|
|
data.get("TotalCharges")
|
|
|
]
|
|
|
|
|
|
|
|
|
features_array = np.array([features])
|
|
|
|
|
|
|
|
|
prediction = model.predict(features_array)
|
|
|
prediction_probability = model.predict_proba(features_array)
|
|
|
|
|
|
|
|
|
churn_label = "Yes" if prediction[0] == 1 else "No"
|
|
|
response = {
|
|
|
"prediction": churn_label,
|
|
|
"probability": {
|
|
|
"No": prediction_probability[0][0],
|
|
|
"Yes": prediction_probability[0][1]
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return jsonify(response)
|
|
|
|
|
|
except Exception as e:
|
|
|
return jsonify({"error": str(e)})
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
app.run(debug=True)
|
|
|
|