BikeSharingDemand / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
4a4315f verified
Raw History Blame Contribute Delete
6.48 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='Bike Sharing Demand (XGBoost)',
page_icon='🚲',
layout='centered'
)
BASE_DIR = Path(__file__).resolve().parent
MODEL_PATH = BASE_DIR / 'xgb_model.pkl'
FEATURE_COLS_BASE = [
'datetime', 'season', 'holiday', 'workingday', 'weather',
'temp', 'atemp', 'humidity', 'windspeed'
]
@st.cache_resource
def load_artifact():
if not MODEL_PATH.exists():
raise FileNotFoundError(
f"Model not found: {MODEL_PATH.name}. Put '{MODEL_PATH.name}' in the repo root (same folder as app.py)."
)
obj = joblib.load(MODEL_PATH)
# If saved as dict: {"model": ..., "feature_cols": [...]}
if isinstance(obj, dict) and 'model' in obj:
model = obj['model']
feature_cols = obj.get('feature_cols', None)
return model, feature_cols, True
# Otherwise: directly the model
return obj, None, False
def add_features(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
df['datetime'] = pd.to_datetime(df['datetime'], errors='coerce')
if df['datetime'].isna().any():
bad = df[df['datetime'].isna()].index.tolist()[:5]
raise ValueError(
f"Some 'datetime' values could not be parsed. Bad rows example index: {bad}. "
f"Use format like 2011-01-20 00:00:00"
)
df['hour'] = df['datetime'].dt.hour.astype(int)
df['weekday'] = df['datetime'].dt.weekday.astype(int)
df['month'] = df['datetime'].dt.month.astype(int)
df['year'] = df['datetime'].dt.year.astype(int)
# engineered features (same as your notebook)
df['frequently'] = df['hour'].isin([6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18]).astype(int)
df['weekend'] = (df['weekday'] >= 5).astype(int)
df['windy'] = (df['windspeed'] > 25).astype(int)
df['best_temp'] = ((df['temp'] >= 15) & (df['temp'] <= 30)).astype(int)
return df
def prepare_x(df_feat: pd.DataFrame, feature_cols: list | None) -> pd.DataFrame:
# drop datetime (your training X did not include datetime)
x = df_feat.drop(columns=['datetime'])
if feature_cols is None:
return x
missing = [c for c in feature_cols if c not in x.columns]
extra = [c for c in x.columns if c not in feature_cols]
if missing:
raise ValueError(f"Missing features for model: {missing}")
# drop extras if any
if extra:
x = x.drop(columns=extra)
# reorder exactly like training
x = x[feature_cols]
return x
def predict_counts(model, x: pd.DataFrame) -> np.ndarray:
pred = model.predict(x)
pred = np.clip(pred, 0, None)
pred = np.rint(pred).astype(int)
return pred
# --- UI ---
st.title('🚲 Bike Sharing Demand Forecast')
st.write('Predict hourly bike rental demand using an XGBoost regression model.')
model, feature_cols, is_artifact = load_artifact()
with st.expander('Model info', expanded=False):
st.write(f"Model file: `{MODEL_PATH.name}`")
st.write(f"Loaded as artifact dict: `{is_artifact}`")
if feature_cols is not None:
st.write(f"Number of model features: `{len(feature_cols)}`")
st.code(', '.join(feature_cols))
tab1, tab2 = st.tabs(['Single Prediction', 'Batch Prediction (CSV)'])
# --- Single prediction ---
with tab1:
st.subheader('Single Prediction')
show_debug = st.checkbox('Show debug info', value=False)
dt = st.text_input('datetime (e.g. 2011-01-20 08:00:00)', value='2011-01-20 08:00:00')
c1, c2 = st.columns(2)
with c1:
season = st.selectbox('season (1=spring, 2=summer, 3=fall, 4=winter)', [1, 2, 3, 4], index=0)
holiday = st.selectbox('holiday', [0, 1], index=0)
workingday = st.selectbox('workingday', [0, 1], index=1)
weather = st.selectbox('weather (1-4)', [1, 2, 3, 4], index=0)
with c2:
temp = st.number_input('temp (°C)', value=20.0)
atemp = st.number_input('atemp (°C)', value=22.0)
humidity = st.number_input('humidity (0-100)', value=60.0, min_value=0.0, max_value=100.0)
windspeed = st.number_input('windspeed', value=10.0, min_value=0.0)
if st.button('Predict'):
try:
row = pd.DataFrame([{
'datetime': dt,
'season': int(season),
'holiday': int(holiday),
'workingday': int(workingday),
'weather': int(weather),
'temp': float(temp),
'atemp': float(atemp),
'humidity': float(humidity),
'windspeed': float(windspeed),
}])
feat = add_features(row)
x_row = prepare_x(feat, feature_cols)
pred_int = predict_counts(model, x_row)[0]
st.success(f"Predicted rentals (count): **{pred_int}**")
if show_debug:
debug_df = feat.copy()
debug_df['prediction'] = pred_int
st.dataframe(debug_df)
except Exception as e:
st.error(str(e))
# --- Batch prediction ---
with tab2:
st.subheader('Batch Prediction (CSV Upload)')
st.write("Upload a CSV like Kaggle `test.csv` with these columns:")
st.code(', '.join(FEATURE_COLS_BASE))
file = st.file_uploader('Upload CSV', type=['csv'])
if file is not None:
try:
df_in = pd.read_csv(file)
missing_base = [c for c in FEATURE_COLS_BASE if c not in df_in.columns]
if missing_base:
st.error(f"Missing columns: {missing_base}")
else:
df_in = df_in[FEATURE_COLS_BASE].copy()
df_feat = add_features(df_in)
x_batch = prepare_x(df_feat, feature_cols)
preds = predict_counts(model, x_batch)
out = pd.DataFrame({
'datetime': df_feat['datetime'],
'count': preds
})
st.success('Predictions created!')
st.dataframe(out.head(20))
csv_bytes = out.to_csv(index=False).encode('utf-8')
st.download_button(
label='Download predictions.csv',
data=csv_bytes,
file_name='predictions.csv',
mime='text/csv'
)
except Exception as e:
st.error(str(e))
st.caption("Model file expected: xgb_model.pkl (repo root).")