malona's picture
Update app.py
ad4e613 verified
Raw History Blame Contribute Delete
2.2 kB
import gradio as gr
import pandas as pd
import pickle
from sklearn.preprocessing import StandardScaler, LabelEncoder
import os
# load sklearn
os.system('pip install scikit-learn==1.2.2')
# Load models, scaler, and encoders
with open('models.pkl', 'rb') as f:
data = pickle.load(f)
lin = data["lin"]
dtree = data["dtree"]
rf = data["rf"]
gbm = data["gbm"]
xg_reg = data["xg_reg"]
scaler = data["scaler"]
city_encoder = data["city_encoder"]
state_encoder = data["state_encoder"]
# Load the data
data_price = pd.read_csv('data_price.csv')
x = data_price.drop(columns=['price'])
# Define input components
inputs = [
gr.Number(label="Bed", value=3),
gr.Number(label="Bath", value=2),
gr.Number(label="Acre Lot", value=0.5),
gr.Dropdown(label="City", choices=x['city'].unique().tolist()),
gr.Dropdown(label="State", choices=x['state'].unique().tolist()),
gr.Number(label="Zip Code", value=94107),
gr.Number(label="House Size", value=2000),
]
# Define output components
outputs = [
gr.Textbox(label="Prediction"),
]
# Define the prediction function
def predict(bed, bath, acre_lot, city, state, zip_code, house_size, street = 0, brokered_by = 0):
# Create a DataFrame with the input data
data = pd.DataFrame(data=[[brokered_by, bed, bath, acre_lot, street, city, state, zip_code, house_size]], columns=x.columns)
# Encode categorical features
data['city'] = city_encoder.transform([city])
data['state'] = state_encoder.transform([state])
# Standardize the user input data
data_scaled = scaler.transform(data)
# Make predictions with each model
predictions = []
for model_name, model in {"lin": lin, "dtree": dtree, "rf": rf, "gbm": gbm, "xg_reg": xg_reg}.items():
predictions.append(f"{model_name}: {model.predict(data_scaled)[0]}")
# Return the predictions
return "\n".join(predictions)
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=inputs,
outputs=outputs,
title="Real Estate Price Prediction App",
description="Select features and get a prediction from each model."
)
# Launch the Gradio interface
iface.launch(debug=True)