Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import seaborn as sns
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.datasets import fetch_california_housing
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.linear_model import LinearRegression
|
| 8 |
+
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
| 9 |
+
|
| 10 |
+
# --- Step 1: Load dataset ---
|
| 11 |
+
data = fetch_california_housing(as_frame=True)
|
| 12 |
+
df = data.frame
|
| 13 |
+
|
| 14 |
+
X = df.drop(columns=['MedHouseVal'])
|
| 15 |
+
y = df['MedHouseVal']
|
| 16 |
+
feature_names = X.columns
|
| 17 |
+
|
| 18 |
+
# --- Step 2: Split dataset ---
|
| 19 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 20 |
+
|
| 21 |
+
# --- Step 3: Train model ---
|
| 22 |
+
model = LinearRegression()
|
| 23 |
+
model.fit(X_train, y_train)
|
| 24 |
+
|
| 25 |
+
# --- Step 4: Evaluate model ---
|
| 26 |
+
y_pred = model.predict(X_test)
|
| 27 |
+
mae = mean_absolute_error(y_test, y_pred)
|
| 28 |
+
mse = mean_squared_error(y_test, y_pred)
|
| 29 |
+
r2 = r2_score(y_test, y_pred)
|
| 30 |
+
|
| 31 |
+
# --- Step 5: Graph 1 - Actual vs Predicted ---
|
| 32 |
+
def plot_actual_vs_predicted():
|
| 33 |
+
fig, ax = plt.subplots(figsize=(5, 4))
|
| 34 |
+
ax.scatter(y_test, y_pred, alpha=0.5)
|
| 35 |
+
ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
|
| 36 |
+
ax.set_xlabel("Actual Prices")
|
| 37 |
+
ax.set_ylabel("Predicted Prices")
|
| 38 |
+
ax.set_title("Actual vs Predicted Prices")
|
| 39 |
+
fig.canvas.draw()
|
| 40 |
+
img = np.array(fig.canvas.renderer.buffer_rgba())
|
| 41 |
+
plt.close(fig)
|
| 42 |
+
return img
|
| 43 |
+
|
| 44 |
+
# --- Step 6: Graph 2 - Feature Importance ---
|
| 45 |
+
def plot_feature_importance():
|
| 46 |
+
importance = np.abs(model.coef_)
|
| 47 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 48 |
+
sns.barplot(x=importance, y=feature_names, palette="coolwarm")
|
| 49 |
+
plt.title("Feature Importance (Linear Regression Coefficients)")
|
| 50 |
+
fig.canvas.draw()
|
| 51 |
+
img = np.array(fig.canvas.renderer.buffer_rgba())
|
| 52 |
+
plt.close(fig)
|
| 53 |
+
return img
|
| 54 |
+
|
| 55 |
+
# --- Step 7: Prediction Function ---
|
| 56 |
+
def predict_price(MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude):
|
| 57 |
+
features = np.array([[MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude]])
|
| 58 |
+
predicted_price = model.predict(features)[0]
|
| 59 |
+
return f"๐ก Predicted Median House Value: ${predicted_price * 100000:.2f}"
|
| 60 |
+
|
| 61 |
+
# --- Step 8: Gradio Interface ---
|
| 62 |
+
with gr.Blocks() as demo:
|
| 63 |
+
gr.Markdown("## ๐ House Price Prediction with Graphs")
|
| 64 |
+
gr.Markdown(f"**Model Performance:** Rยฒ = {r2:.2f}, MAE = {mae:.2f}, MSE = {mse:.2f}")
|
| 65 |
+
|
| 66 |
+
with gr.Row():
|
| 67 |
+
MedInc = gr.Number(label="Median Income (10k USD)")
|
| 68 |
+
HouseAge = gr.Number(label="House Age (years)")
|
| 69 |
+
AveRooms = gr.Number(label="Average Rooms per House")
|
| 70 |
+
AveBedrms = gr.Number(label="Average Bedrooms per House")
|
| 71 |
+
Population = gr.Number(label="Population in Block")
|
| 72 |
+
AveOccup = gr.Number(label="Average Occupancy")
|
| 73 |
+
Latitude = gr.Number(label="Latitude")
|
| 74 |
+
Longitude = gr.Number(label="Longitude")
|
| 75 |
+
|
| 76 |
+
output_text = gr.Textbox(label="Prediction Result")
|
| 77 |
+
|
| 78 |
+
predict_btn = gr.Button("๐ Predict House Price")
|
| 79 |
+
predict_btn.click(
|
| 80 |
+
predict_price,
|
| 81 |
+
inputs=[MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude],
|
| 82 |
+
outputs=output_text
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
gr.Markdown("### ๐ Model Performance Graphs")
|
| 86 |
+
gr.Image(value=plot_actual_vs_predicted(), label="Actual vs Predicted Prices")
|
| 87 |
+
gr.Image(value=plot_feature_importance(), label="Feature Importance")
|
| 88 |
+
|
| 89 |
+
# --- Step 9: Launch the app ---
|
| 90 |
+
demo.launch()
|