churn_rate / app.py
dkb007's picture
Upload 4 files
5821a4b verified
from flask import Flask, request, jsonify
import joblib
import numpy as np
# Initialize the Flask app
app = Flask(__name__)
# Load the trained model
model = joblib.load('random_forest_model.pkl')
@app.route('/')
def home():
return "Welcome to the Customer Churn Prediction API!"
# Define the prediction endpoint
@app.route('/predict', methods=['POST'])
def predict():
try:
# Get the JSON data from the request
data = request.get_json()
# Extract features from the input 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")
]
# Convert the features to a NumPy array for the model
features_array = np.array([features])
# Perform prediction
prediction = model.predict(features_array)
prediction_probability = model.predict_proba(features_array)
# Map prediction result to a human-readable label
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)})
# Run the app
if __name__ == '__main__':
app.run(debug=True)