EnYa32's picture
Update src/streamlit_app.py
3c57d80 verified
Raw History Blame Contribute Delete
4.66 kB
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",
)