File size: 1,885 Bytes
7756657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer

class ChurnPredictionInput(BaseModel):
    customer_features: List[float]

class ChurnPredictionOutput(BaseModel):
    churn_probability: float
    churn_prediction: bool

class ChurnPredictionAPI:
    def __init__(self, model_path):
        # Load pre-trained model and tokenizer
        self.model = AutoModelForSequenceClassification.from_pretrained("random_forest_model.pkl")
        self.model.eval()  # Set model to evaluation mode

    def predict(self, customer_features):
        # Convert input to tensor
        input_tensor = torch.tensor([customer_features], dtype=torch.float32)
        
        # Make prediction
        with torch.no_grad():
            outputs = self.model(input_tensor)
            probabilities = torch.softmax(outputs.logits, dim=1)
            churn_prob = probabilities[0][1].item()  # Probability of churn class
        
        return {
            'churn_probability': churn_prob,
            'churn_prediction': churn_prob > 0.5
        }

# Create FastAPI app
app = FastAPI(
    title="Customer Churn Prediction API",
    description="API for predicting customer churn probability"
)

# Initialize the churn prediction model
churn_predictor = ChurnPredictionAPI("random_forest_model.pkl")

@app.post("/predict", response_model=ChurnPredictionOutput)
async def predict_churn(input: ChurnPredictionInput):
    try:
        prediction = churn_predictor.predict(input.customer_features)
        return prediction
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

# Run the API
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)