File size: 2,998 Bytes
9e03a51 | 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 | 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()
|