Spaces:
Runtime error
Runtime error
File size: 3,399 Bytes
25bb26a | 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 | import gradio as gr
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# --- Step 1: Load dataset ---
data = fetch_california_housing(as_frame=True)
df = data.frame
X = df.drop(columns=['MedHouseVal'])
y = df['MedHouseVal']
feature_names = X.columns
# --- Step 2: Split dataset ---
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# --- Step 3: Train model ---
model = LinearRegression()
model.fit(X_train, y_train)
# --- Step 4: Evaluate model ---
y_pred = model.predict(X_test)
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# --- Step 5: Graph 1 - Actual vs Predicted ---
def plot_actual_vs_predicted():
fig, ax = plt.subplots(figsize=(5, 4))
ax.scatter(y_test, y_pred, alpha=0.5)
ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
ax.set_xlabel("Actual Prices")
ax.set_ylabel("Predicted Prices")
ax.set_title("Actual vs Predicted Prices")
fig.canvas.draw()
img = np.array(fig.canvas.renderer.buffer_rgba())
plt.close(fig)
return img
# --- Step 6: Graph 2 - Feature Importance ---
def plot_feature_importance():
importance = np.abs(model.coef_)
fig, ax = plt.subplots(figsize=(6, 4))
sns.barplot(x=importance, y=feature_names, palette="coolwarm")
plt.title("Feature Importance (Linear Regression Coefficients)")
fig.canvas.draw()
img = np.array(fig.canvas.renderer.buffer_rgba())
plt.close(fig)
return img
# --- Step 7: Prediction Function ---
def predict_price(MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude):
features = np.array([[MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude]])
predicted_price = model.predict(features)[0]
return f"๐ก Predicted Median House Value: ${predicted_price * 100000:.2f}"
# --- Step 8: Gradio Interface ---
with gr.Blocks() as demo:
gr.Markdown("## ๐ House Price Prediction with Graphs")
gr.Markdown(f"**Model Performance:** Rยฒ = {r2:.2f}, MAE = {mae:.2f}, MSE = {mse:.2f}")
with gr.Row():
MedInc = gr.Number(label="Median Income (10k USD)")
HouseAge = gr.Number(label="House Age (years)")
AveRooms = gr.Number(label="Average Rooms per House")
AveBedrms = gr.Number(label="Average Bedrooms per House")
Population = gr.Number(label="Population in Block")
AveOccup = gr.Number(label="Average Occupancy")
Latitude = gr.Number(label="Latitude")
Longitude = gr.Number(label="Longitude")
output_text = gr.Textbox(label="Prediction Result")
predict_btn = gr.Button("๐ Predict House Price")
predict_btn.click(
predict_price,
inputs=[MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude],
outputs=output_text
)
gr.Markdown("### ๐ Model Performance Graphs")
gr.Image(value=plot_actual_vs_predicted(), label="Actual vs Predicted Prices")
gr.Image(value=plot_feature_importance(), label="Feature Importance")
# --- Step 9: Launch the app ---
demo.launch() |