Spaces:
Sleeping

File size: 6,939 Bytes
a289188
8625b3d
a289188
 
 
 
8625b3d
a289188
 
 
 
 
 
 
8625b3d
 
a289188
 
 
 
 
 
8625b3d
a289188
8625b3d
a289188
 
 
 
 
 
 
 
 
 
 
8625b3d
a289188
 
 
 
 
8625b3d
 
 
 
a289188
 
 
 
 
8625b3d
 
a289188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8625b3d
a289188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8625b3d
a289188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
{% extends "base.html" %}
{% block title %}Supervised Learning - Data Science Lab{% endblock %}

{% block content %}
<div class="page-header">
    <h1>🎯 Supervised Learning</h1>
    <p class="breadcrumb">Home / Supervised — Regression & Classification with data</p>
</div>

<div class="concept-section">
    <div class="concept-header"><h3>📖 What is Supervised Learning?</h3></div>
    <div class="concept-body">
        <p>Supervised learning trains models on labeled data — each input has a known output. The model learns the mapping from features (X) to target (y).</p>
        <table class="table">
            <tr><th>Task</th><th>Output</th><th>Example</th><th>Algorithm</th></tr>
            <tr><td>Regression</td><td>Continuous number</td><td>Predict property price</td><td>Linear Regression, Random Forest</td></tr>
            <tr><td>Classification</td><td>Category label</td><td>Classify feedback sentiment</td><td>Logistic Regression, SVM</td></tr>
        </table>
    </div>
</div>

<div class="concept-section">
    <div class="concept-header"><h3>🚀 Train Price Models</h3></div>
    <div class="concept-body">
        <p>Train regression models on housing data. Make sure data is loaded first (run pipeline from the Pipeline page).</p>

        <div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 15px;">
            <button class="btn" onclick="trainModel('linear_regression')">📈 Linear Regression</button>
            <button class="btn" onclick="trainModel('random_forest')">🌲 Random Forest</button>
        </div>

        <div id="model-output" class="output-box" style="min-height: 100px;"></div>
    </div>
</div>

<div class="concept-section">
    <div class="concept-header"><h3>🔮 Predict housing Price</h3></div>
    <div class="concept-body">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 15px;">
            <div>
                <label>Town</label>
                <select id="pred-town" class="form-control">
                    <option>DOWNTOWN</option><option>MIDTOWN</option>
                    <option>WESTSIDE</option><option>LAKESIDE</option>
                    <option>HILLVIEW</option><option>HARBOR</option>
                    <option>NORTHPARK</option><option>RIVERSIDE</option>
                </select>
            </div>
            <div>
                <label>Flat Type</label>
                <select id="pred-flat" class="form-control">
                    <option>SMALL</option><option>MEDIUM</option>
                    <option>LARGE</option><option>PREMIUM</option>
                </select>
            </div>
            <div>
                <label>Floor Area (sqm)</label>
                <input type="number" id="pred-area" class="form-control" value="95" min="40" max="200">
            </div>
            <div>
                <label>Storey (mid-point)</label>
                <input type="number" id="pred-storey" class="form-control" value="10" min="1" max="50">
            </div>
            <div>
                <label>Lease Remaining (years)</label>
                <input type="number" id="pred-lease" class="form-control" value="85" min="40" max="99">
            </div>
        </div>
        <button class="btn" onclick="predictPrice()">💰 Predict Price</button>
        <div id="predict-output" class="output-box" style="margin-top: 15px; min-height: 60px;"></div>
    </div>
</div>

<div class="concept-section">
    <div class="concept-header"><h3>📖 Model Evaluation</h3></div>
    <div class="concept-body">
        <div class="code-block"><span class="lang-label">Python</span><pre>from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error

# After training
y_pred = model.predict(X_test)

# Regression metrics
mse = mean_squared_error(y_test, y_pred)
rmse = mse ** 0.5
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"RMSE: ${rmse:,.0f}")    # Average prediction error in dollars
print(f"MAE:  ${mae:,.0f}")     # Median-like error
print(f"R²:   {r2:.4f}")       # % of variance explained (1.0 = perfect)

# Interpretation for price model:
# RMSE = $45,000 means our predictions are ±$45K on average
# R² = 0.82 means 82% of price variation is explained by our features</pre></div>

        <h4>Train/Test Split — Why It Matters</h4>
        <div class="code-block"><span class="lang-label">Python</span><pre>from sklearn.model_selection import train_test_split, cross_val_score

# Split: 80% train, 20% test
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Better: K-Fold Cross Validation
scores = cross_val_score(model, X, y, cv=5, scoring='r2')
print(f"CV R² scores: {scores}")
print(f"Mean R²: {scores.mean():.4f} ± {scores.std():.4f}")</pre></div>
    </div>
</div>

<div class="concept-section">
    <div class="concept-header"><h3>📜 Model Training History</h3></div>
    <div class="concept-body">
        <button class="btn btn-secondary" onclick="loadModelHistory()">Load History</button>
        <div id="model-history" style="margin-top: 15px;">
            <table class="table" id="model-history-table">
                <thead><tr><th>Model</th><th>R²</th><th>RMSE</th><th>MAE</th><th>Trained</th></tr></thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<div class="common-mistake">
    <h5>⚠️ Common Mistakes</h5>
    <ul>
        <li><strong>Data leakage</strong>: Fitting scaler on full data before splitting ⇒ optimistic metrics</li>
        <li><strong>Not encoding categoricals properly</strong>: Random Forest expects numerical inputs</li>
        <li><strong>Ignoring feature importance</strong>: Random Forest can tell you which features matter most</li>
    </ul>
</div>

<div class="exercise-box">
    <h5>🧪 Exercises</h5>
    <p>1. Train both models and compare their R² and RMSE. Which performs better?</p>
    <p>2. Predict prices for the same flat in different towns. What's the price premium for central locations?</p>
    <p>3. Why might the model perform poorly for PREMIUM flats?</p>
</div>

<script>
function loadModelHistory() {
    apiCall('/api/model/history', 'GET').then(data => {
        const tbody = document.querySelector('#model-history-table tbody');
        tbody.innerHTML = '';
        if (data.history) {
            data.history.forEach(row => {
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${row.model_name}</td><td>${row.r2_score ? row.r2_score.toFixed(4) : '-'}</td>
                    <td>${row.rmse ? '$' + row.rmse.toFixed(0) : '-'}</td>
                    <td>${row.mae ? '$' + row.mae.toFixed(0) : '-'}</td>
                    <td>${row.trained_at || '-'}</td>`;
                tbody.appendChild(tr);
            });
        }
    });
}
</script>
{% endblock %}