Spaces:
Runtime error
Runtime error
| import pandas as pd | |
| import numpy as np | |
| # Feature columns exactly as trained | |
| FEATURE_COLUMNS = [ | |
| 'Customer Service Calls', | |
| 'Monthly Charge', | |
| 'Contract Type', | |
| 'Account Length', | |
| 'Avg Monthly GB Download', | |
| ] | |
| CONTRACT_MAP = { | |
| 'Month-to-Month': 0, | |
| 'One Year': 1, | |
| 'Two Year': 2, | |
| } | |
| def preprocess_single(input_dict: dict) -> pd.DataFrame: | |
| """Preprocess a single customer input dict.""" | |
| df = pd.DataFrame([input_dict]) | |
| return _preprocess(df) | |
| def preprocess_batch(df: pd.DataFrame) -> pd.DataFrame: | |
| """Preprocess a batch DataFrame.""" | |
| df = df.copy() | |
| # Drop ID or label columns if present | |
| for col in ['Customer ID', 'CustomerID', 'Churn', 'Churn Label']: | |
| if col in df.columns: | |
| df = df.drop(columns=[col]) | |
| return _preprocess(df) | |
| def _preprocess(df: pd.DataFrame) -> pd.DataFrame: | |
| df = df.copy() | |
| # Encode Contract Type | |
| if 'Contract Type' in df.columns: | |
| df['Contract Type'] = df['Contract Type'].map(CONTRACT_MAP).fillna(0).astype(int) | |
| # Numeric coercion | |
| for col in ['Customer Service Calls', 'Monthly Charge', | |
| 'Account Length', 'Avg Monthly GB Download']: | |
| if col in df.columns: | |
| df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0) | |
| # Ensure all columns exist | |
| for col in FEATURE_COLUMNS: | |
| if col not in df.columns: | |
| df[col] = 0 | |
| return df[FEATURE_COLUMNS] | |
| def get_sample_csv() -> str: | |
| return ( | |
| "Customer ID,Customer Service Calls,Monthly Charge," | |
| "Contract Type,Account Length,Avg Monthly GB Download\n" | |
| "C001,4,85.50,Month-to-Month,12,32.1\n" | |
| "C002,1,55.00,One Year,36,18.5\n" | |
| "C003,7,110.00,Month-to-Month,6,55.0\n" | |
| "C004,0,45.00,Two Year,60,10.2\n" | |
| "C005,3,75.00,Month-to-Month,24,28.7\n" | |
| ) | |