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 - 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 - Feature Importance (coefficients) --- 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") gr.Image(value=plot_feature_importance(), label="Feature Importance") # --- Step 9: Launch the app --- demo.launch()