Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
|
6 |
+
# Global variable to store history of attempts
|
7 |
+
history = []
|
8 |
+
|
9 |
+
def predict_house_price(area):
|
10 |
+
"""Simple house price prediction based on area"""
|
11 |
+
# Using the simple formula: price = 0.1 * area (as per your slides)
|
12 |
+
price = 0.1 * area
|
13 |
+
return float(price)
|
14 |
+
|
15 |
+
def calculate_sse(x, y, m, b):
|
16 |
+
"""Calculate Sum of Squared Errors"""
|
17 |
+
y_predicted = m * x + b
|
18 |
+
sse = np.sum((y - y_predicted) ** 2)
|
19 |
+
return sse
|
20 |
+
|
21 |
+
def plot_regression(data, m, b):
|
22 |
+
try:
|
23 |
+
df = data if isinstance(data, pd.DataFrame) else pd.read_csv(data)
|
24 |
+
df['X'] = pd.to_numeric(df['X'])
|
25 |
+
df['Y'] = pd.to_numeric(df['Y'])
|
26 |
+
|
27 |
+
sse = calculate_sse(df['X'], df['Y'], m, b)
|
28 |
+
|
29 |
+
history.append({
|
30 |
+
'm': m,
|
31 |
+
'b': b,
|
32 |
+
'sse': sse,
|
33 |
+
'color': plt.cm.rainbow(len(history) % 10 / 10)
|
34 |
+
})
|
35 |
+
|
36 |
+
fig = plt.figure(figsize=(15, 6))
|
37 |
+
|
38 |
+
# First subplot - Regression lines
|
39 |
+
ax1 = fig.add_subplot(121)
|
40 |
+
ax1.scatter(df['X'], df['Y'], color='black', alpha=0.5, label='Data points')
|
41 |
+
|
42 |
+
for i, attempt in enumerate(history):
|
43 |
+
x_range = np.linspace(df['X'].min(), df['X'].max(), 100)
|
44 |
+
y_line = attempt['m'] * x_range + attempt['b']
|
45 |
+
label = f"m={attempt['m']:.1f}, b={attempt['b']:.1f}"
|
46 |
+
ax1.plot(x_range, y_line, color=attempt['color'], linewidth=2,
|
47 |
+
label=f"Try {i+1}: {label}")
|
48 |
+
|
49 |
+
ax1.set_xlabel('X')
|
50 |
+
ax1.set_ylabel('Y')
|
51 |
+
ax1.set_title('Linear Regression Attempts')
|
52 |
+
ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
53 |
+
|
54 |
+
# Second subplot - SSE values
|
55 |
+
ax2 = fig.add_subplot(122)
|
56 |
+
attempts = range(1, len(history) + 1)
|
57 |
+
sse_values = [attempt['sse'] for attempt in history]
|
58 |
+
colors = [attempt['color'] for attempt in history]
|
59 |
+
|
60 |
+
ax2.scatter(attempts, sse_values, c=colors)
|
61 |
+
ax2.plot(attempts, sse_values, 'gray', alpha=0.3)
|
62 |
+
|
63 |
+
for i, (attempt, sse) in enumerate(zip(attempts, sse_values)):
|
64 |
+
label = f"m={history[i]['m']:.1f}\nb={history[i]['b']:.1f}"
|
65 |
+
ax2.annotate(label, (attempt, sse),
|
66 |
+
xytext=(5, 5), textcoords='offset points')
|
67 |
+
|
68 |
+
ax2.set_xlabel('Attempt Number')
|
69 |
+
ax2.set_ylabel('Sum of Squared Errors')
|
70 |
+
ax2.set_title('SSE for Each Attempt')
|
71 |
+
ax2.grid(True, alpha=0.3)
|
72 |
+
|
73 |
+
plt.tight_layout()
|
74 |
+
plt.close()
|
75 |
+
return fig
|
76 |
+
|
77 |
+
except Exception as e:
|
78 |
+
print(f"Error: {e}")
|
79 |
+
return None
|
80 |
+
|
81 |
+
def clear_history():
|
82 |
+
history.clear()
|
83 |
+
return None
|
84 |
+
|
85 |
+
# Create the Gradio interface with tabs
|
86 |
+
with gr.Blocks() as app:
|
87 |
+
gr.Markdown("# Linear Regression Learning Tools")
|
88 |
+
|
89 |
+
with gr.Tabs():
|
90 |
+
# First Tab - House Price Prediction
|
91 |
+
with gr.TabItem("House Price Predictor"):
|
92 |
+
gr.Markdown("""
|
93 |
+
# House Price Predictor
|
94 |
+
Enter the area of the house (in m²) to predict its price.
|
95 |
+
Based on the simple model: Price = 0.1 × Area
|
96 |
+
""")
|
97 |
+
|
98 |
+
with gr.Row():
|
99 |
+
area_input = gr.Number(
|
100 |
+
label="House Area (m²)",
|
101 |
+
value=100
|
102 |
+
)
|
103 |
+
price_output = gr.Number(
|
104 |
+
label="Predicted Price ($M)",
|
105 |
+
value=None
|
106 |
+
)
|
107 |
+
|
108 |
+
predict_button = gr.Button("Predict Price")
|
109 |
+
predict_button.click(
|
110 |
+
fn=predict_house_price,
|
111 |
+
inputs=area_input,
|
112 |
+
outputs=price_output
|
113 |
+
)
|
114 |
+
|
115 |
+
# Example table
|
116 |
+
gr.Markdown("""
|
117 |
+
### Example Data Points:
|
118 |
+
| Area (m²) | Price ($M) |
|
119 |
+
|-----------|------------|
|
120 |
+
| 100 | 10 |
|
121 |
+
| 200 | 20 |
|
122 |
+
| 300 | 30 |
|
123 |
+
| 400 | 40 |
|
124 |
+
| 500 | 50 |
|
125 |
+
""")
|
126 |
+
|
127 |
+
# Second Tab - Regression Playground
|
128 |
+
with gr.TabItem("Regression Playground"):
|
129 |
+
gr.Markdown("""
|
130 |
+
# Linear Regression Playground
|
131 |
+
Explore how slope (m) and intercept (b) affect the line of best fit:
|
132 |
+
- Enter data points in the table
|
133 |
+
- Adjust the sliders to fit the line
|
134 |
+
- Click Submit to see your attempt
|
135 |
+
""")
|
136 |
+
|
137 |
+
with gr.Row():
|
138 |
+
data_input = gr.Dataframe(
|
139 |
+
headers=["X", "Y"],
|
140 |
+
datatype=["number", "number"],
|
141 |
+
row_count=5,
|
142 |
+
col_count=2,
|
143 |
+
label="Dataset",
|
144 |
+
interactive=True,
|
145 |
+
value=[[100, 10],
|
146 |
+
[200, 20],
|
147 |
+
[300, 30],
|
148 |
+
[400, 40],
|
149 |
+
[500, 50]]
|
150 |
+
)
|
151 |
+
|
152 |
+
with gr.Column():
|
153 |
+
m_slider = gr.Slider(
|
154 |
+
minimum=-10,
|
155 |
+
maximum=10,
|
156 |
+
value=1.0,
|
157 |
+
step=0.1,
|
158 |
+
label="Slope (m)",
|
159 |
+
)
|
160 |
+
|
161 |
+
b_slider = gr.Slider(
|
162 |
+
minimum=-10,
|
163 |
+
maximum=10,
|
164 |
+
value=0.0,
|
165 |
+
step=0.1,
|
166 |
+
label="Intercept (b)",
|
167 |
+
)
|
168 |
+
|
169 |
+
submit_button = gr.Button("Submit")
|
170 |
+
clear_button = gr.Button("Clear History")
|
171 |
+
|
172 |
+
plot_output = gr.Plot()
|
173 |
+
|
174 |
+
# Set up the event handlers
|
175 |
+
inputs = [data_input, m_slider, b_slider]
|
176 |
+
clear_button.click(fn=clear_history, inputs=None, outputs=plot_output)
|
177 |
+
submit_button.click(fn=plot_regression, inputs=inputs, outputs=plot_output)
|
178 |
+
|
179 |
+
if __name__ == "__main__":
|
180 |
+
app.launch(show_api=False)
|