Download model.py from kddkb/churn_rate: direct link, hf CLI and curl.
- Browser
- Download file 1.89 kB
-
https://huggingface.co/kddkb/churn_rate/resolve/main/model.py
- Command line
-
hf download hf://kddkb/churn_rate/model.py
-
curl -L -o model.py https://huggingface.co/kddkb/churn_rate/resolve/main/model.py
1.89 kB
| 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") | |
| 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) |