Spaces:
Runtime error
Runtime error
File size: 4,663 Bytes
23d0ffd 3c57d80 23d0ffd 3c57d80 | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | import numpy as np
import pandas as pd
import streamlit as st
import joblib
from pathlib import Path
st.set_page_config(
page_title="Santander Transaction Prediction (LightGBM)",
page_icon="🏦",
layout="wide",
)
BASE_DIR = Path(__file__).resolve().parent
MODEL_PATH = BASE_DIR / "lightgbm_santander_model.pkl" # <- ggf. anpassen
@st.cache_resource
def load_model(path: Path):
if not path.exists():
raise FileNotFoundError(
f"Model file not found: {path.name}. Put it in the repo root (same folder as app.py)."
)
obj = joblib.load(path)
# supports either plain model or dict artifact {"model":..., "features":[...], "threshold":...}
if isinstance(obj, dict) and "model" in obj:
model = obj["model"]
features = obj.get("features", None)
default_threshold = float(obj.get("threshold", 0.5))
return model, features, default_threshold
return obj, None, 0.5
def ensure_feature_order(df: pd.DataFrame, feature_list):
"""Return X with correct feature order."""
if feature_list is not None:
missing = [c for c in feature_list if c not in df.columns]
extra = [c for c in df.columns if c not in feature_list]
return df[feature_list], missing, extra
# If no stored feature list: assume Santander var_0..var_199
expected = [f"var_{i}" for i in range(200)]
missing = [c for c in expected if c not in df.columns]
extra = [c for c in df.columns if c not in expected]
# If expected columns exist, use them; else fallback to current columns
if len(missing) == 0:
return df[expected], [], extra
return df, missing, extra
st.title("🏦 Santander Customer Transaction Prediction")
st.write(
"This app predicts the probability that a customer will make a specific transaction "
"using a trained **LightGBM** model."
)
# Load model
try:
model, saved_features, saved_default_threshold = load_model(MODEL_PATH)
except Exception as e:
st.error(str(e))
st.stop()
with st.sidebar:
st.header("Settings")
threshold = st.slider(
"Classification threshold (for label only)",
min_value=0.0,
max_value=1.0,
value=float(saved_default_threshold),
step=0.01,
)
st.caption("Note: Kaggle uses probabilities (ROC-AUC). Threshold is for label display only.")
st.subheader("1) Upload test data (CSV)")
st.write(
"Upload a CSV with columns **ID_code** and **var_0 ... var_199**. "
"You can upload the original Kaggle `test.csv`."
)
uploaded = st.file_uploader("Choose a CSV file", type=["csv"])
if uploaded is None:
st.info("Upload a CSV to get predictions. (Tip: use Kaggle `test.csv`.)")
st.stop()
df = pd.read_csv(uploaded)
if "ID_code" in df.columns:
ids = df["ID_code"].astype(str)
X = df.drop(columns=["ID_code"])
else:
ids = pd.Series([f"row_{i}" for i in range(len(df))])
X = df.copy()
X, missing_cols, extra_cols = ensure_feature_order(X, saved_features)
if missing_cols:
st.error(
"Missing required columns. Please upload a file with the correct feature columns.\n\n"
f"Missing (showing up to 15): {missing_cols[:15]}"
)
st.stop()
if extra_cols:
st.warning(
"Your file contains extra columns that are not used by the model. "
f"(showing up to 15): {extra_cols[:15]}"
)
# Predict probabilities
proba = model.predict_proba(X)[:, 1]
pred_label = (proba >= threshold).astype(int)
st.subheader("2) Results")
col1, col2, col3 = st.columns(3)
col1.metric("Rows", f"{len(df):,}")
col2.metric("Mean probability", f"{np.mean(proba):.4f}")
col3.metric("Predicted positives", f"{int(pred_label.sum()):,}")
result = pd.DataFrame(
{
"ID_code": ids.values,
"probability": proba,
"prediction": pred_label,
}
)
st.dataframe(result.head(20), use_container_width=True)
st.subheader("3) Download predictions")
csv_out = result.to_csv(index=False).encode("utf-8")
st.download_button(
label="Download predictions as CSV",
data=csv_out,
file_name="predictions_lightgbm.csv",
mime="text/csv",
)
st.caption(
"For Kaggle submission: rename columns to **ID_code** and **target** "
"and submit probabilities (no threshold)."
)
# Kaggle submission helper
st.subheader("4) Kaggle submission format (optional)")
sub = pd.DataFrame({"ID_code": ids.values, "target": proba})
st.dataframe(sub.head(10), use_container_width=True)
sub_csv = sub.to_csv(index=False).encode("utf-8")
st.download_button(
label="Download Kaggle submission CSV",
data=sub_csv,
file_name="submission_lightgbm.csv",
mime="text/csv",
) |