Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from sklearn.datasets import fetch_california_housing
|
| 5 |
+
from sklearn.linear_model import LinearRegression
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.metrics import mean_squared_error
|
| 8 |
+
|
| 9 |
+
# Load dataset directly from sklearn (safe for Hugging Face Spaces)
|
| 10 |
+
def load_data():
|
| 11 |
+
data = fetch_california_housing(as_frame=True, data_home="/tmp")
|
| 12 |
+
return data.frame
|
| 13 |
+
|
| 14 |
+
# Train model once at startup
|
| 15 |
+
def train_model():
|
| 16 |
+
df = load_data()
|
| 17 |
+
X = df.drop("MedHouseVal", axis=1)
|
| 18 |
+
y = df["MedHouseVal"]
|
| 19 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 20 |
+
|
| 21 |
+
model = LinearRegression()
|
| 22 |
+
model.fit(X_train, y_train)
|
| 23 |
+
mse = mean_squared_error(y_test, model.predict(X_test))
|
| 24 |
+
return model, mse
|
| 25 |
+
|
| 26 |
+
model, mse = train_model()
|
| 27 |
+
|
| 28 |
+
# Prediction function
|
| 29 |
+
def predict(MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude):
|
| 30 |
+
input_array = np.array([[MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude]])
|
| 31 |
+
prediction = model.predict(input_array)[0]
|
| 32 |
+
return f"Estimated Median House Value: ${prediction * 100000:.2f}"
|
| 33 |
+
|
| 34 |
+
# Gradio UI
|
| 35 |
+
inputs = [
|
| 36 |
+
gr.Number(label="Median Income"),
|
| 37 |
+
gr.Number(label="House Age"),
|
| 38 |
+
gr.Number(label="Average Rooms"),
|
| 39 |
+
gr.Number(label="Average Bedrooms"),
|
| 40 |
+
gr.Number(label="Population"),
|
| 41 |
+
gr.Number(label="Average Occupancy"),
|
| 42 |
+
gr.Number(label="Latitude"),
|
| 43 |
+
gr.Number(label="Longitude"),
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
iface = gr.Interface(
|
| 47 |
+
fn=predict,
|
| 48 |
+
inputs=inputs,
|
| 49 |
+
outputs="text",
|
| 50 |
+
title="🏠 California House Price Predictor",
|
| 51 |
+
description=f"Trained on California housing data. Model MSE: {mse:.4f}",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
iface.launch()
|