| from __future__ import annotations |
|
|
| from pathlib import Path |
|
|
| import gradio as gr |
|
|
| from src.data import load_training_data |
| from src.modeling import DEFAULT_MODEL_PATH, HousePriceModel, train_model |
|
|
|
|
| MODEL_PATH = Path(DEFAULT_MODEL_PATH) |
|
|
|
|
| def ensure_model() -> HousePriceModel: |
| if not MODEL_PATH.exists(): |
| train_model(load_training_data(), artifact_path=MODEL_PATH) |
| return HousePriceModel.load(MODEL_PATH) |
|
|
|
|
| MODEL = ensure_model() |
|
|
|
|
| def predict_price( |
| overall_qual: int, |
| gr_liv_area: int, |
| garage_cars: int, |
| total_bsmt_sf: int, |
| full_bath: int, |
| year_built: int, |
| neighborhood: str, |
| house_style: str, |
| ) -> str: |
| prediction = MODEL.predict( |
| { |
| "OverallQual": overall_qual, |
| "GrLivArea": gr_liv_area, |
| "GarageCars": garage_cars, |
| "TotalBsmtSF": total_bsmt_sf, |
| "FullBath": full_bath, |
| "YearBuilt": year_built, |
| "Neighborhood": neighborhood, |
| "HouseStyle": house_style, |
| } |
| ) |
| return f"${prediction:,.0f}" |
|
|
|
|
| with gr.Blocks(title="House Price Predictor") as demo: |
| gr.Markdown("# House Price Predictor") |
| gr.Markdown("Predict sale prices using a model trained on the Kaggle House Prices dataset.") |
|
|
| with gr.Row(): |
| with gr.Column(): |
| overall_qual = gr.Slider(1, 10, value=7, step=1, label="Overall quality") |
| gr_liv_area = gr.Number(value=1800, label="Above-ground living area") |
| garage_cars = gr.Slider(0, 5, value=2, step=1, label="Garage capacity") |
| total_bsmt_sf = gr.Number(value=1000, label="Total basement square feet") |
| with gr.Column(): |
| full_bath = gr.Slider(0, 5, value=2, step=1, label="Full bathrooms") |
| year_built = gr.Number(value=1995, label="Year built") |
| neighborhood = gr.Dropdown( |
| ["NAmes", "CollgCr", "OldTown", "Edwards", "Somerst", "NridgHt", "Gilbert", "NoRidge"], |
| value="Somerst", |
| label="Neighborhood", |
| allow_custom_value=True, |
| ) |
| house_style = gr.Dropdown( |
| ["1Story", "2Story", "1.5Fin", "SLvl", "SFoyer"], |
| value="2Story", |
| label="House style", |
| allow_custom_value=True, |
| ) |
|
|
| output = gr.Textbox(label="Predicted sale price", interactive=False) |
| predict_button = gr.Button("Predict", variant="primary") |
| predict_button.click( |
| fn=predict_price, |
| inputs=[ |
| overall_qual, |
| gr_liv_area, |
| garage_cars, |
| total_bsmt_sf, |
| full_bath, |
| year_built, |
| neighborhood, |
| house_style, |
| ], |
| outputs=output, |
| api_name="predict", |
| ) |
|
|
| gr.Markdown( |
| f"Model metrics: RMSE `{MODEL.metrics.get('rmse')}`, " |
| f"MAE `{MODEL.metrics.get('mae')}`, R2 `{MODEL.metrics.get('r2')}`" |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| demo.launch() |
|
|
|
|