File size: 2,094 Bytes
5821a4b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
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)
|