deedrop1140 commited on
Commit
a62ac7b
·
verified ·
1 Parent(s): 732949b

Update templates/Random_Forest_Classifier.html

Browse files
Files changed (1) hide show
  1. templates/Random_Forest_Classifier.html +548 -471
templates/Random_Forest_Classifier.html CHANGED
@@ -3,490 +3,567 @@
3
  {% block content %}<!DOCTYPE html>
4
  <html lang="en">
5
  <head>
6
-     <meta charset="UTF-8">
7
-     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>🔬 Visual Random Forest Classifier (2D)</title>
8
-    <script src="https://cdn.plot.ly/plotly-2.32.0.min.js"></script>
9
-
10
-       <script src="https://cdn.tailwindcss.com"></script>
11
-     <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
12
-     <style>
13
-         /* Basic styling for info icons and tooltips */
14
-         .info-icon {
15
-             cursor: help;
16
-             margin-left: 5px;
17
-             color: #6B7280; /* gray-500 */
18
-             position: relative; /* Needed for tooltip positioning */
19
-             display: inline-block;
20
-         }
21
-         .tooltip {
22
-             visibility: hidden;
23
-             width: 250px; /* Wider for more detail */
24
-             background-color: #333;
25
-             color: #fff;
26
-             text-align: center;
27
-             border-radius: 6px;
28
-             padding: 8px 10px; /* More padding */
29
-             position: absolute;
30
-             z-index: 10; /* Above other elements */
31
-             bottom: 125%; /* Position above the icon */
32
-             left: 50%;
33
-             margin-left: -125px; /* Center the tooltip */
34
-             opacity: 0;
35
-             transition: opacity 0.3s;
36
-             font-size: 0.85rem; /* Slightly smaller font for tooltips */
37
-             line-height: 1.4;
38
-         }
39
-         .info-icon:hover .tooltip {
40
-             visibility: visible;
41
-             opacity: 1;
42
-         }
43
-         /* Triangle for tooltip (optional) */
44
-         .tooltip::after {
45
-             content: "";
46
-             position: absolute;
47
-             top: 100%;
48
-             left: 50%;
49
-             margin-left: -5px;
50
-             border-width: 5px;
51
-             border-style: solid;
52
-             border-color: #333 transparent transparent transparent;
53
-         }
54
-
55
-         /* Styling for highlighting text in explanations */
56
-         .highlight-blue { color: #2563EB; font-weight: 600; } /* Tailwind blue-600 */
57
-         .highlight-red { color: #DC2626; font-weight: 600; }  /* Tailwind red-600 */
58
-         .highlight-green { color: #16A34A; font-weight: 600; } /* Tailwind green-600 */
59
-         .highlight-bold { font-weight: 600; }
60
-
61
-         /* Styles for the flow chart boxes (reusing from KNN) */
62
-         .flow-box {
63
-             background-color: #F3F4F6; /* gray-100 */
64
-             border-radius: 0.5rem; /* rounded-lg */
65
-             padding: 1.5rem; /* p-6 */
66
-             text-align: center;
67
-             box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* shadow-md */
68
-             min-height: 120px; /* Ensure boxes have some height */
69
-             display: flex;
70
-             flex-direction: column;
71
-             justify-content: center;
72
-             align-items: center;
73
-         }
74
-         .flow-arrow {
75
-             font-size: 2.5rem;
76
-             color: #9CA3AF; /* gray-400 */
77
-             margin: 0 1rem;
78
-             display: flex;
79
-             align-items: center;
80
-             justify-content: center;
81
-         }
82
-     </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  </head>
84
 
85
  <body class="bg-gray-100 text-gray-900">
86
-         <div class="max-w-full sm:max-w-5xl mx-2 sm:mx-auto mt-4 sm:mt-10 bg-white p-4 sm:p-8 rounded-xl shadow-lg">
87
-         <h1 class="text-3xl font-bold mb-4 text-center">🔬 Visual Random Forest Classifier (2D)</h1>
88
-         <p class="mb-6 text-center text-gray-600">
89
-             An ensemble learning method for classification that operates by constructing a multitude of decision trees.
90
-         </p>
91
-
92
-                 <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
93
-             <div>
94
-                 <label for="testX" class="block font-medium mb-1 flex items-center">
95
-                     Test Point X1:
96
-                     <span class="info-icon">
97
-                         &#9432;
98
-                         <span class="tooltip">
99
-                             The <span class="highlight-bold">X1-coordinate</span> of the new data point (<span class="highlight-green">green 'x'</span>) that you want the Random Forest to classify.
100
-                         </span>
101
-                     </span>
102
-                 </label>
103
-                                 <input type="number" id="testX" value="4" class="w-full md:w-24 px-2 py-1 border rounded" onchange="predict()">
104
-             </div>
105
-
106
-             <div>
107
-                 <label for="testY" class="block font-medium mb-1 flex items-center">
108
-                     Test Point X2:
109
-                     <span class="info-icon">
110
-                         &#9432;
111
-                         <span class="tooltip">
112
-                             The <span class="highlight-bold">X2-coordinate</span> of the new data point (<span class="highlight-green">green 'x'</span>) that you want the Random Forest to classify.
113
-                         </span>
114
-                     </span>
115
-                 </label>
116
-                                 <input type="number" id="testY" value="2" class="w-full md:w-24 px-2 py-1 border rounded" onchange="predict()">
117
-             </div>
118
-         </div>
119
-
120
-         <div class="mb-4 text-center">
121
-             <button onclick="predict()" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg text-lg transition duration-200 w-full sm:w-auto">
122
-                 Run Random Forest Prediction
123
-             </button>
124
-         </div>
125
-
126
-                 <div id="plot" class="border rounded-lg shadow-inner w-full" style="height: 500px;"></div>
127
-         <p id="result" class="mt-4 font-bold text-lg text-center text-gray-800"></p>
128
-
129
-         <div class="mt-10 p-6 bg-purple-50 rounded-xl border border-purple-200">
130
-             <h2 class="text-2xl font-bold mb-6 text-center text-purple-700">How Random Forest Classifies Your Data</h2>
131
-                         <div class="flex flex-wrap justify-center items-center gap-4">
132
-                 <div class="flow-box bg-purple-100">
133
-                     <span class="text-5xl mb-2">🌳</span>
134
-                     <p class="text-lg font-semibold text-purple-800">Many Decision Trees</p>
135
-                     <p class="text-sm text-purple-600">Each trained on a random subset</p>
136
-                 </div>
137
-                                 <div class="flow-arrow hidden md:flex">&rarr;</div>
138
- <div class="flow-arrow flex md:hidden">&darr;</div>
139
-                 <div class="flow-box bg-purple-100">
140
-                     <span class="text-5xl mb-2">📍</span>
141
-                     <p class="text-lg font-semibold text-purple-800">New Data Point</p>
142
-                     <p class="text-sm text-purple-600">Sent to ALL trees</p>
143
-                 </div>
144
-                                 <div class="flow-arrow hidden md:flex">&rarr;</div>
145
- <div class="flow-arrow flex md:hidden">&darr;</div>
146
-                 <div class="flow-box bg-purple-100">
147
-                     <span class="text-5xl mb-2">📊</span>
148
-                     <p class="text-lg font-semibold text-purple-800">Individual Predictions</p>
149
-                     <p class="text-sm text-purple-600">Each tree "votes" on the class</p>
150
-                 </div>
151
-                                 <div class="flow-arrow hidden md:flex">&rarr;</div>
152
- <div class="flow-arrow flex md:hidden">&darr;</div>
153
-                 <div class="flow-box bg-purple-100">
154
-                     <span class="text-5xl mb-2">🗳️</span>
155
-                     <p class="text-lg font-semibold text-purple-800">Majority Vote</p>
156
-                     <p class="text-sm text-purple-600">Most common prediction wins</p>
157
-                 </div>
158
-                                 <div class="flow-arrow hidden md:flex">&rarr;</div>
159
- <div class="flow-arrow flex md:hidden">&darr;</div>
160
-                 <div class="flow-box bg-purple-100">
161
-                     <span class="text-5xl mb-2">✅</span>
162
-                     <p class="text-lg font-semibold text-purple-800">Final Classification</p>
163
-                     <p class="text-sm text-purple-600">Robust and accurate</p>
164
-                 </div>
165
-             </div>
166
-
167
-
168
-             <p class="mt-6 text-center text-gray-600 text-sm">
169
-                 Random Forest combines the power of many individual decision trees to make a more robust and accurate classification, leveraging collective intelligence.
170
-             </p>
171
-         </div>
172
-
173
-         <div class="mt-8 text-center">
174
  <a href="/liar" class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700">
175
-   🔍 Go to Liar Predictor
176
  </a>
177
 
178
 
179
 
180
-         <div class="mt-8 p-6 bg-gray-50 rounded-lg border border-gray-200">
181
-             <h2 class="text-2xl font-bold mb-4 text-center text-blue-700">Understanding Random Forest</h2>
182
-
183
-             <p class="mb-4 text-gray-700">
184
-                 Random Forest is an <span class="highlight-bold">ensemble learning method</span> that builds a "forest" of decision trees. For classification tasks, it outputs the class that is the mode of the classes (majority vote) of the individual trees. It's known for its high accuracy and ability to handle complex datasets.
185
-             </p>
186
-
187
-             <h3 class="text-xl font-semibold mb-2">Key Concepts:</h3>
188
-             <ul class="list-disc list-inside text-gray-700 mb-4">
189
-                 <li class="mb-2">
190
-                     <span class="highlight-bold">Ensemble Learning:</span> Instead of relying on a single model, Random Forest combines predictions from multiple models (decision trees) to improve overall accuracy and robustness.
191
-                 </li>
192
-                 <li class="mb-2">
193
-                     <span class="highlight-bold">Decision Trees:</span> Each tree in the forest makes a prediction independently. A single decision tree creates axis-parallel splits, leading to rectangular decision regions.
194
-                 </li>
195
-                 <li class="mb-2">
196
-                     <span class="highlight-bold">Randomness:</span> Random Forest introduces randomness in two ways:
197
-                     <ol class="list-decimal list-inside ml-4">
198
-                         <li><span class="highlight-bold">Bagging (Bootstrap Aggregating):</span> Each tree is trained on a random subset of the training data (with replacement).</li>
199
-               ��         <li><span class="highlight-bold">Feature Randomness:</span> When splitting a node, each tree considers only a random subset of the available features. This decorrelates the trees.</li>
200
-                     </ol>
201
-                 </li>
202
-                 <li class="mb-2">
203
-                     <span class="highlight-bold">Decision Boundary:</span> Unlike a single decision tree's sharp, rectangular boundaries, the Random Forest's decision boundary is the aggregated result of many trees. This often results in a smoother, more complex, and often non-linear boundary, as seen in the plot.
204
-                 </li>
205
-             </ul>
206
-
207
-             <h3 class="text-xl font-semibold mb-2">How this Visualization Works:</h3>
208
-             <ul class="list-disc list-inside text-gray-700 mb-4">
209
-                 <li class="mb-2">
210
-                     <span class="highlight-red">Class 1 (Red Circles):</span> These are your labeled data points belonging to Class 1.
211
-                 </li>
212
-                 <li class="mb-2">
213
-                     <span class="highlight-blue">Class 0 (Blue Circles):</span> These are your labeled data points belonging to Class 0.
214
-                 </li>
215
-                 <li class="mb-2">
216
-                     <span class="highlight-green">Test Point (Green 'x'):</span> This is the new, unlabeled data point you want to classify. You can adjust its X1 and X2 coordinates.
217
-                 </li>
218
-                 <li class="mb-2">
219
-                     <span class="highlight-bold">Colored Background:</span> This represents the <span class="highlight-bold">decision boundary</span> of the trained Random Forest model.
220
-                     <ul>
221
-                         <li><span class="highlight-red">Red regions</span> indicate areas where the Random Forest predicts Class 1.</li>
222
-                         <li><span class="highlight-blue">Blue regions</span> indicate areas where the Random Forest predicts Class 0.</li>
223
-                     </ul>
224
-                     The smoothness and complexity of this boundary are a result of the ensemble nature of Random Forest.
225
-                 </li>
226
-             </ul>
227
-
228
-             <p class="mt-4 text-sm text-gray-600">
229
-                 *The plot will show the decision boundary by predicting the class for a grid of points covering the entire plot area. The color of each grid point reflects the predicted class, creating the background regions.*
230
-             </p>
231
-         </div>
232
-     </div>
233
-
234
-     <script>
235
-         // Sample labeled points (training data) - you can adjust these
236
-         // Using distinct clusters for better visualization of decision boundary
237
-         let labeledPoints = [
238
-             // Class 0 (Blue)
239
-             [1.0, 1.0, 0], [1.5, 1.8, 0], [2.0, 1.2, 0], [1.2, 2.5, 0], [2.5, 2.0, 0],
240
-             [3.0, 1.0, 0], [3.5, 2.2, 0], [2.8, 0.5, 0], [1.8, 0.8, 0], [0.5, 2.0, 0],
241
-             [0.8, 3.0, 0], [2.2, 3.5, 0], [3.2, 3.0, 0], [4.0, 2.5, 0], [4.5, 1.8, 0],
242
-
243
-             // Class 1 (Red)
244
-             [5.0, 5.0, 1], [5.5, 4.2, 1], [6.0, 5.8, 1], [4.8, 6.0, 1], [6.2, 6.5, 1],
245
-             [7.0, 5.0, 1], [6.5, 4.0, 1], [5.8, 6.8, 1], [7.2, 6.0, 1], [7.8, 5.5, 1],
246
-             [8.0, 7.0, 1], [7.5, 7.5, 1], [6.8, 7.2, 1], [5.2, 7.8, 1], [4.0, 6.0, 1]
247
-         ];
248
-
249
-         function getTestPoint() {
250
-             const testXInput = document.getElementById('testX');
251
-             const testYInput = document.getElementById('testY');
252
-
253
-             const testX = parseFloat(testXInput.value);
254
-             const testY = parseFloat(testYInput.value);
255
-
256
-             if (isNaN(testX) || isNaN(testY)) {
257
-                 document.getElementById("result").innerText = "❌ Please enter valid numbers for Test Point X1 and X2.";
258
-                 testXInput.value = 4; // Reset to default
259
-                 testYInput.value = 2; // Reset to default
260
-                 return null;
261
-             }
262
-             return [testX, testY];
263
-         }
264
-
265
-         async function predict() {
266
-             const testPoint = getTestPoint();
267
-             if (testPoint === null) {
268
-                 return; // Stop if testPoint input is invalid
269
-             }
270
-
271
-             document.getElementById("result").innerText = "Calculating decision boundary and prediction...";
272
-
273
-             console.log("Predicting with test point =", testPoint);
274
-
275
-             // *** API Call to your Python Backend ***
276
-             const res = await fetch("/rf_visual_predict", {
277
-                 method: "POST",
278
-                 headers: { 'Content-Type': 'application/json' },
279
-                 body: JSON.stringify({
280
-                     points: labeledPoints,
281
-                     test_point: testPoint
282
-                     // You could add n_estimators, max_depth here if you want them interactive
283
-                 })
284
-             });
285
-
286
-             if (!res.ok) {
287
-                 document.getElementById("result").innerText = `❌ Error from backend: ${res.statusText}. Ensure your Flask backend is running.`;
288
-                 console.error("Backend error:", res.statusText);
289
-                 return;
290
-             }
291
-
292
-             const data = await res.json();
293
-             console.log("Response:", data);
294
-
295
-             document.getElementById("result").innerText = `✅ Predicted Class for (${testPoint[0]}, ${testPoint[1]}): ${data.prediction == 0 ? 'Class 0 (Blue)' : 'Class 1 (Red)'}`;
296
-
297
-             // Prepare traces for Plotly
298
-             const class0 = labeledPoints.filter(p => p[2] == 0);
299
-             const class1 = labeledPoints.filter(p => p[2] == 1);
300
-
301
-             const trace0 = {
302
-                 x: class0.map(p => p[0]),
303
-                 y: class0.map(p => p[1]),
304
-                 mode: 'markers',
305
-                 name: 'Class 0',
306
-                 marker: { color: 'blue', size: 10, symbol: 'circle' }
307
-             };
308
-
309
-             const trace1 = {
310
-                 x: class1.map(p => p[0]),
311
-                 y: class1.map(p => p[1]),
312
-                 mode: 'markers',
313
-                 name: 'Class 1',
314
-                 marker: { color: 'red', size: 10, symbol: 'circle' }
315
-             };
316
-
317
-             const testTrace = {
318
-                 x: [testPoint[0]],
319
-                 y: [testPoint[1]],
320
-                 mode: 'markers',
321
-                 name: 'Test Point',
322
-                 marker: { color: 'green', size: 14, symbol: 'x' }
323
-             };
324
-
325
-             // Decision Boundary (Contour/Heatmap)
326
-             // The 'z' data comes from the backend, representing predictions on a grid
327
-             const boundaryTrace = {
328
-                 z: data.decision_boundary_z,
329
-                 x: data.decision_boundary_x_coords, // X coordinates of the grid
330
-                 y: data.decision_boundary_y_coords, // Y coordinates of the grid
331
-                 type: 'contour',
332
-                 colorscale: [
333
-                     ['0.0', 'rgba(0, 0, 255, 0.2)'], // Light blue for Class 0
334
-                     ['1.0', 'rgba(255, 0, 0, 0.2)']  // Light red for Class 1
335
-                 ],
336
-                 showscale: false, // No color bar needed
337
-                 hoverinfo: 'skip', // Don't show hover details for the boundary
338
-                 opacity: 0.8 // Make it slightly transparent
339
-             };
340
-
341
-             // Plotly layout and redraw
342
-             Plotly.newPlot('plot', [boundaryTrace, trace0, trace1, testTrace], {
343
-                 title: `Random Forest Decision Boundary`,
344
-                 xaxis: { title: 'X1', range: [0, 9] }, // Adjust range based on your data
345
-                 yaxis: { title: 'X2', range: [0, 9] }, // Adjust range
346
-                 height: 500,
347
-                 hovermode: 'closest',
348
-                 autosize: true // ADDED: Ensure plot adjusts to container size
349
-             });
350
-         }
351
-
352
-         window.onload = () => {
353
-             predict();
354
-             Plotly.relayout('plot', { autosize: true }); // Ensure plot is sized correctly on load
355
-         };
356
-     </script>
357
-         <div class="mt-12 bg-white rounded-lg shadow-lg p-6 border border-gray-300"> 
358
-   <h2 class="text-2xl font-bold text-center text-purple-700 mb-4">🌳 Single Tree vs Random Forest</h2>
359
-     <div id="treeComparisonPlot" class="w-full" style="height: 500px;"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  </div>
361
 
362
  <script>
363
-   const singleTreeTrace = {
364
-     type: "scatter",
365
-     mode: "markers+lines+text",
366
-     x: [2, 1, 3, 0.5, 1.5, 2.5, 3.5],
367
-     y: [3, 2, 2, 1, 1, 1, 1],
368
-     text: ["Root", "", "", "class 1", "class 1", "class 2", "class 2"],
369
-     textposition: "top center",
370
-     marker: { size: 30, color: "royalblue" },
371
-     line: { color: 'royalblue', width: 2 },
372
-     name: "Single Decision Tree",
373
-     showlegend: false,
374
-     xaxis: 'x1',
375
-     yaxis: 'y1'
376
-   };
377
-
378
-   const forestTraces = [
379
-     {
380
-       type: "scatter",
381
-       mode: "markers+lines+text",
382
-       x: [7, 6.5, 7.5],
383
-       y: [3, 2, 2],
384
-       text: ["Tree 1", "class 1", "class 1"],
385
-       textposition: "top center",
386
-       marker: { size: 28, color: "red" },
387
-       line: { color: 'red', width: 2 },
388
-       showlegend: false,
389
-       xaxis: 'x2',
390
-       yaxis: 'y2'
391
-     },
392
-     {
393
-       type: "scatter",
394
-       mode: "markers+lines+text",
395
-       x: [9, 8.5, 9.5],
396
-       y: [3, 2, 2],
397
-       text: ["Tree 2", "class 2", "class 2"],
398
-       textposition: "top center",
399
-       marker: { size: 28, color: "green" },
400
-       line: { color: 'green', width: 2 },
401
-       showlegend: false,
402
-       xaxis: 'x2',
403
-       yaxis: 'y2'
404
-     },
405
-     {
406
-       type: "scatter",
407
-       mode: "markers+lines+text",
408
-       x: [11, 10.5, 11.5],
409
-       y: [3, 2, 2],
410
-       text: ["Tree 3", "class 3", "class 3"],
411
-       textposition: "top center",
412
-       marker: { size: 28, color: "orange" },
413
-       line: { color: 'orange', width: 2 },
414
-       showlegend: false,
415
-       xaxis: 'x2',
416
-       yaxis: 'y2'
417
-     }
418
-   ];
419
-
420
-   const layout = {
421
-     // MODIFIED: Adjust column width for mobile (0.45 and 0.55 are relative to total width)
422
-     grid: { rows: 1, columns: 2, pattern: 'independent' },
423
-     xaxis: {
424
-       domain: [0, 0.45],
425
-       title: { text: "Single Decision Tree", font: { size: 14 } },
426
-       showgrid: false,
427
-       zeroline: false
428
-     },
429
-     yaxis: {
430
-       domain: [0, 1],
431
-       showgrid: false,
432
-       zeroline: false
433
-     },
434
-     xaxis2: {
435
-       domain: [0.55, 1],
436
-       title: { text: "Random Forest (Multiple Trees)", font: { size: 14 } },
437
-       showgrid: false,
438
-       zeroline: false
439
-     },
440
-     yaxis2: {
441
-       domain: [0, 1],
442
-       showgrid: false,
443
-       zeroline: false
444
-     },
445
-     showlegend: false,
446
-     height: 500,
447
-     margin: { t: 30, b: 40 },
448
-     title: {
449
-       text: "📊 Visualizing Decision Tree vs Random Forest",
450
-       font: { size: 18 }
451
-     },
452
-     autosize: true // ADDED: Ensure plot adjusts to container size
453
-   };
454
-
455
-   Plotly.newPlot('treeComparisonPlot', [singleTreeTrace, ...forestTraces], layout, {responsive: true}); // ADDED: responsive: true for Plotly to manage resize
456
  </script>
457
-     <div class="mt-8 text-gray-800 space-y-4">
458
-     <h3 class="text-xl font-bold text-blue-700">🔍 Working of Random Forest Algorithm</h3>
459
-     <ul class="list-disc list-inside space-y-2">
460
-       <li><strong>Create Many Decision Trees:</strong> The algorithm makes many decision trees using different random parts of the data.</li>
461
-       <li><strong>Pick Random Features:</strong> Each tree picks a random subset of features to make splits. This keeps trees diverse.</li>
462
-       <li><strong>Each Tree Makes a Prediction:</strong> Every tree gives its own output.</li>
463
-       <li><strong>Combine the Predictions:</strong>
464
-         <ul class="ml-6 list-disc">
465
-           <li><em>Classification:</em> Uses majority voting across trees.</li>
466
-           <li><em>Regression:</em> Averages the outputs of all trees.</li>
467
-         </ul>
468
-       </li>
469
-       <li><strong>Why It Works:</strong> Randomness prevents overfitting and improves overall prediction accuracy.</li>
470
-     </ul>
471
-
472
-     <h3 class="text-xl font-bold text-blue-700 mt-6">🌟 Key Features of Random Forest</h3>
473
-     <ul class="list-disc list-inside space-y-2">
474
-       <li><strong>Handles Missing Data:</strong> Works even with some missing values.</li>
475
-       <li><strong>Shows Feature Importance:</strong> Identifies most important features for prediction.</li>
476
-       <li><strong>Handles Complex Data:</strong> Efficient with large datasets and many features.</li>
477
-       <li><strong>Versatile:</strong> Works for both classification and regression tasks.</li>
478
-     </ul>
479
-
480
-     <h3 class="text-xl font-bold text-blue-700 mt-6">📌 Assumptions of Random Forest</h3>
481
-     <ul class="list-disc list-inside space-y-2">
482
-       <li>Each tree is independent and makes its own prediction.</li>
483
-       <li>Each tree is trained on random samples and features.</li>
484
-       <li>A large enough dataset is required for diverse learning.</li>
485
-       <li>Combining different trees improves accuracy.</li>
486
-     </ul>
487
-   </div>
 
488
  </div>
489
 
490
  </body>
491
  </html>
492
- {% endblock %}
 
3
  {% block content %}<!DOCTYPE html>
4
  <html lang="en">
5
  <head>
6
+ <meta charset="UTF-8">
7
+ <title>🔬 Visual Random Forest Classifier (2D)</title>
8
+ <script src="https://cdn.plot.ly/plotly-2.32.0.min.js"></script>
9
+
10
+ <script src="https://cdn.tailwindcss.com"></script>
11
+ <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
12
+ <style>
13
+ /* Basic styling for info icons and tooltips */
14
+ .info-icon {
15
+ cursor: help;
16
+ margin-left: 5px;
17
+ color: #6B7280; /* gray-500 */
18
+ position: relative; /* Needed for tooltip positioning */
19
+ display: inline-block;
20
+ }
21
+ .tooltip {
22
+ visibility: hidden;
23
+ width: 250px; /* Wider for more detail */
24
+ background-color: #333;
25
+ color: #fff;
26
+ text-align: center;
27
+ border-radius: 6px;
28
+ padding: 8px 10px; /* More padding */
29
+ position: absolute;
30
+ z-index: 10; /* Above other elements */
31
+ bottom: 125%; /* Position above the icon */
32
+ left: 50%;
33
+ margin-left: -125px; /* Center the tooltip */
34
+ opacity: 0;
35
+ transition: opacity 0.3s;
36
+ font-size: 0.85rem; /* Slightly smaller font for tooltips */
37
+ line-height: 1.4;
38
+ }
39
+ .info-icon:hover .tooltip {
40
+ visibility: visible;
41
+ opacity: 1;
42
+ }
43
+ /* Triangle for tooltip (optional) */
44
+ .tooltip::after {
45
+ content: "";
46
+ position: absolute;
47
+ top: 100%;
48
+ left: 50%;
49
+ margin-left: -5px;
50
+ border-width: 5px;
51
+ border-style: solid;
52
+ border-color: #333 transparent transparent transparent;
53
+ }
54
+
55
+ /* Styling for highlighting text in explanations */
56
+ .highlight-blue { color: #2563EB; font-weight: 600; } /* Tailwind blue-600 */
57
+ .highlight-red { color: #DC2626; font-weight: 600; } /* Tailwind red-600 */
58
+ .highlight-green { color: #16A34A; font-weight: 600; } /* Tailwind green-600 */
59
+ .highlight-bold { font-weight: 600; }
60
+
61
+ /* Styles for the flow chart boxes (reusing from KNN) */
62
+ .flow-box {
63
+ background-color: #F3F4F6; /* gray-100 */
64
+ border-radius: 0.5rem; /* rounded-lg */
65
+ padding: 1.5rem; /* p-6 */
66
+ text-align: center;
67
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* shadow-md */
68
+ min-height: 120px; /* Ensure boxes have some height */
69
+ display: flex;
70
+ flex-direction: column;
71
+ justify-content: center;
72
+ align-items: center;
73
+ }
74
+ .flow-arrow {
75
+ font-size: 2.5rem;
76
+ color: #9CA3AF; /* gray-400 */
77
+ margin: 0 1rem;
78
+ display: flex;
79
+ align-items: center;
80
+ justify-content: center;
81
+ }
82
+
83
+ /* --- Responsive adjustments for mobile --- */
84
+ /* Ensure plot containers take full width but smaller height on narrow screens */
85
+ #plot, #treeComparisonPlot {
86
+ width: 100%;
87
+ /* default desktop height; Plotly layout height controls actual plot height */
88
+ max-width: 100%;
89
+ }
90
+
91
+ /* On small screens make fonts and some paddings lighter so layout feels compact */
92
+ @media (max-width: 640px) {
93
+ body { font-size: 14px; }
94
+ .text-3xl { font-size: 1.5rem; } /* smaller headline on mobile */
95
+ .flow-box { padding: 1rem; min-height: 90px; }
96
+ .flow-box span.text-5xl { font-size: 2rem; } /* shrink emojis */
97
+ .flow-arrow { font-size: 1.8rem; margin: 0 .5rem; }
98
+
99
+ /* Give plots lower heights on small screens */
100
+ /* Plot height will be programmatically set via JS, but this gives a CSS fallback */
101
+ #plot { height: 320px !important; }
102
+ #treeComparisonPlot { height: 320px !important; }
103
+ }
104
+ /* End responsive adjustments */
105
+ </style>
106
  </head>
107
 
108
  <body class="bg-gray-100 text-gray-900">
109
+ <div class="max-w-5xl mx-auto mt-10 bg-white p-8 rounded-xl shadow-lg">
110
+ <h1 class="text-3xl font-bold mb-4 text-center">🔬 Visual Random Forest Classifier (2D)</h1>
111
+ <p class="mb-6 text-center text-gray-600">
112
+ An ensemble learning method for classification that operates by constructing a multitude of decision trees.
113
+ </p>
114
+
115
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
116
+ <div>
117
+ <label for="testX" class="block font-medium mb-1 flex items-center">
118
+ Test Point X1:
119
+ <span class="info-icon">
120
+ &#9432;
121
+ <span class="tooltip">
122
+ The <span class="highlight-bold">X1-coordinate</span> of the new data point (<span class="highlight-green">green 'x'</span>) that you want the Random Forest to classify.
123
+ </span>
124
+ </span>
125
+ </label>
126
+ <input type="number" id="testX" value="4" class="w-24 px-2 py-1 border rounded" onchange="predict()">
127
+ </div>
128
+
129
+ <div>
130
+ <label for="testY" class="block font-medium mb-1 flex items-center">
131
+ Test Point X2:
132
+ <span class="info-icon">
133
+ &#9432;
134
+ <span class="tooltip">
135
+ The <span class="highlight-bold">X2-coordinate</span> of the new data point (<span class="highlight-green">green 'x'</span>) that you want the Random Forest to classify.
136
+ </span>
137
+ </span>
138
+ </label>
139
+ <input type="number" id="testY" value="2" class="w-24 px-2 py-1 border rounded" onchange="predict()">
140
+ </div>
141
+ </div>
142
+
143
+ <div class="mb-4 text-center">
144
+ <button onclick="predict()" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg text-lg transition duration-200">
145
+ Run Random Forest Prediction
146
+ </button>
147
+ </div>
148
+
149
+ <div id="plot" class="border rounded-lg shadow-inner" style="height: 500px; width: 100%;"></div>
150
+ <p id="result" class="mt-4 font-bold text-lg text-center text-gray-800"></p>
151
+
152
+ <div class="mt-10 p-6 bg-purple-50 rounded-xl border border-purple-200">
153
+ <h2 class="text-2xl font-bold mb-6 text-center text-purple-700">How Random Forest Classifies Your Data</h2>
154
+ <div class="flex flex-wrap justify-center items-center gap-4">
155
+ <div class="flow-box bg-purple-100">
156
+ <span class="text-5xl mb-2">🌳</span>
157
+ <p class="text-lg font-semibold text-purple-800">Many Decision Trees</p>
158
+ <p class="text-sm text-purple-600">Each trained on a random subset</p>
159
+ </div>
160
+ <div class="flow-arrow">&rarr;</div>
161
+ <div class="flow-box bg-purple-100">
162
+ <span class="text-5xl mb-2">📍</span>
163
+ <p class="text-lg font-semibold text-purple-800">New Data Point</p>
164
+ <p class="text-sm text-purple-600">Sent to ALL trees</p>
165
+ </div>
166
+ <div class="flow-arrow">&rarr;</div>
167
+ <div class="flow-box bg-purple-100">
168
+ <span class="text-5xl mb-2">📊</span>
169
+ <p class="text-lg font-semibold text-purple-800">Individual Predictions</p>
170
+ <p class="text-sm text-purple-600">Each tree "votes" on the class</p>
171
+ </div>
172
+ <div class="flow-arrow block md:hidden">&darr;</div>
173
+ <div class="flow-arrow hidden md:block">&rarr;</div>
174
+ <div class="flow-box bg-purple-100">
175
+ <span class="text-5xl mb-2">🗳️</span>
176
+ <p class="text-lg font-semibold text-purple-800">Majority Vote</p>
177
+ <p class="text-sm text-purple-600">Most common prediction wins</p>
178
+ </div>
179
+ <div class="flow-arrow">&rarr;</div>
180
+ <div class="flow-box bg-purple-100">
181
+ <span class="text-5xl mb-2">✅</span>
182
+ <p class="text-lg font-semibold text-purple-800">Final Classification</p>
183
+ <p class="text-sm text-purple-600">Robust and accurate</p>
184
+ </div>
185
+ </div>
186
+
187
+
188
+ <p class="mt-6 text-center text-gray-600 text-sm">
189
+ Random Forest combines the power of many individual decision trees to make a more robust and accurate classification, leveraging collective intelligence.
190
+ </p>
191
+ </div>
192
+
193
+ <div class="mt-8 text-center">
 
 
 
194
  <a href="/liar" class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700">
195
+ 🔍 Go to Liar Predictor
196
  </a>
197
 
198
 
199
 
200
+ <div class="mt-8 p-6 bg-gray-50 rounded-lg border border-gray-200">
201
+ <h2 class="text-2xl font-bold mb-4 text-center text-blue-700">Understanding Random Forest</h2>
202
+
203
+ <p class="mb-4 text-gray-700">
204
+ Random Forest is an <span class="highlight-bold">ensemble learning method</span> that builds a "forest" of decision trees. For classification tasks, it outputs the class that is the mode of the classes (majority vote) of the individual trees. It's known for its high accuracy and ability to handle complex datasets.
205
+ </p>
206
+
207
+ <h3 class="text-xl font-semibold mb-2">Key Concepts:</h3>
208
+ <ul class="list-disc list-inside text-gray-700 mb-4">
209
+ <li class="mb-2">
210
+ <span class="highlight-bold">Ensemble Learning:</span> Instead of relying on a single model, Random Forest combines predictions from multiple models (decision trees) to improve overall accuracy and robustness.
211
+ </li>
212
+ <li class="mb-2">
213
+ <span class="highlight-bold">Decision Trees:</span> Each tree in the forest makes a prediction independently. A single decision tree creates axis-parallel splits, leading to rectangular decision regions.
214
+ </li>
215
+ <li class="mb-2">
216
+ <span class="highlight-bold">Randomness:</span> Random Forest introduces randomness in two ways:
217
+ <ol class="list-decimal list-inside ml-4">
218
+ <li><span class="highlight-bold">Bagging (Bootstrap Aggregating):</span> Each tree is trained on a random subset of the training data (with replacement).</li>
219
+ <li><span class="highlight-bold">Feature Randomness:</span> When splitting a node, each tree considers only a random subset of the available features. This decorrelates the trees.</li>
220
+ </ol>
221
+ </li>
222
+ <li class="mb-2">
223
+ <span class="highlight-bold">Decision Boundary:</span> Unlike a single decision tree's sharp, rectangular boundaries, the Random Forest's decision boundary is the aggregated result of many trees. This often results in a smoother, more complex, and often non-linear boundary, as seen in the plot.
224
+ </li>
225
+ </ul>
226
+
227
+ <h3 class="text-xl font-semibold mb-2">How this Visualization Works:</h3>
228
+ <ul class="list-disc list-inside text-gray-700 mb-4">
229
+ <li class="mb-2">
230
+ <span class="highlight-red">Class 1 (Red Circles):</span> These are your labeled data points belonging to Class 1.
231
+ </li>
232
+ <li class="mb-2">
233
+ <span class="highlight-blue">Class 0 (Blue Circles):</span> These are your labeled data points belonging to Class 0.
234
+ </li>
235
+ <li class="mb-2">
236
+ <span class="highlight-green">Test Point (Green 'x'):</span> This is the new, unlabeled data point you want to classify. You can adjust its X1 and X2 coordinates.
237
+ </li>
238
+ <li class="mb-2">
239
+ <span class="highlight-bold">Colored Background:</span> This represents the <span class="highlight-bold">decision boundary</span> of the trained Random Forest model.
240
+ <ul>
241
+ <li><span class="highlight-red">Red regions</span> indicate areas where the Random Forest predicts Class 1.</li>
242
+ <li><span class="highlight-blue">Blue regions</span> indicate areas where the Random Forest predicts Class 0.</li>
243
+ </ul>
244
+ The smoothness and complexity of this boundary are a result of the ensemble nature of Random Forest.
245
+ </li>
246
+ </ul>
247
+
248
+ <p class="mt-4 text-sm text-gray-600">
249
+ *The plot will show the decision boundary by predicting the class for a grid of points covering the entire plot area. The color of each grid point reflects the predicted class, creating the background regions.*
250
+ </p>
251
+ </div>
252
+ </div>
253
+
254
+ <script>
255
+ // Sample labeled points (training data) - you can adjust these
256
+ // Using distinct clusters for better visualization of decision boundary
257
+ let labeledPoints = [
258
+ // Class 0 (Blue)
259
+ [1.0, 1.0, 0], [1.5, 1.8, 0], [2.0, 1.2, 0], [1.2, 2.5, 0], [2.5, 2.0, 0],
260
+ [3.0, 1.0, 0], [3.5, 2.2, 0], [2.8, 0.5, 0], [1.8, 0.8, 0], [0.5, 2.0, 0],
261
+ [0.8, 3.0, 0], [2.2, 3.5, 0], [3.2, 3.0, 0], [4.0, 2.5, 0], [4.5, 1.8, 0],
262
+
263
+ // Class 1 (Red)
264
+ [5.0, 5.0, 1], [5.5, 4.2, 1], [6.0, 5.8, 1], [4.8, 6.0, 1], [6.2, 6.5, 1],
265
+ [7.0, 5.0, 1], [6.5, 4.0, 1], [5.8, 6.8, 1], [7.2, 6.0, 1], [7.8, 5.5, 1],
266
+ [8.0, 7.0, 1], [7.5, 7.5, 1], [6.8, 7.2, 1], [5.2, 7.8, 1], [4.0, 6.0, 1]
267
+ ];
268
+
269
+ function getTestPoint() {
270
+ const testXInput = document.getElementById('testX');
271
+ const testYInput = document.getElementById('testY');
272
+
273
+ const testX = parseFloat(testXInput.value);
274
+ const testY = parseFloat(testYInput.value);
275
+
276
+ if (isNaN(testX) || isNaN(testY)) {
277
+ document.getElementById("result").innerText = "❌ Please enter valid numbers for Test Point X1 and X2.";
278
+ testXInput.value = 4; // Reset to default
279
+ testYInput.value = 2; // Reset to default
280
+ return null;
281
+ }
282
+ return [testX, testY];
283
+ }
284
+
285
+ async function predict() {
286
+ const testPoint = getTestPoint();
287
+ if (testPoint === null) {
288
+ return; // Stop if testPoint input is invalid
289
+ }
290
+
291
+ document.getElementById("result").innerText = "Calculating decision boundary and prediction...";
292
+
293
+ console.log("Predicting with test point =", testPoint);
294
+
295
+ // *** API Call to your Python Backend ***
296
+ const res = await fetch("/rf_visual_predict", {
297
+ method: "POST",
298
+ headers: { 'Content-Type': 'application/json' },
299
+ body: JSON.stringify({
300
+ points: labeledPoints,
301
+ test_point: testPoint
302
+ // You could add n_estimators, max_depth here if you want them interactive
303
+ })
304
+ });
305
+
306
+ if (!res.ok) {
307
+ document.getElementById("result").innerText = `❌ Error from backend: ${res.statusText}. Ensure your Flask backend is running.`;
308
+ console.error("Backend error:", res.statusText);
309
+ return;
310
+ }
311
+
312
+ const data = await res.json();
313
+ console.log("Response:", data);
314
+
315
+ document.getElementById("result").innerText = `✅ Predicted Class for (${testPoint[0]}, ${testPoint[1]}): ${data.prediction == 0 ? 'Class 0 (Blue)' : 'Class 1 (Red)'}`;
316
+
317
+ // Prepare traces for Plotly
318
+ const class0 = labeledPoints.filter(p => p[2] == 0);
319
+ const class1 = labeledPoints.filter(p => p[2] == 1);
320
+
321
+ const trace0 = {
322
+ x: class0.map(p => p[0]),
323
+ y: class0.map(p => p[1]),
324
+ mode: 'markers',
325
+ name: 'Class 0',
326
+ marker: { color: 'blue', size: 10, symbol: 'circle' }
327
+ };
328
+
329
+ const trace1 = {
330
+ x: class1.map(p => p[0]),
331
+ y: class1.map(p => p[1]),
332
+ mode: 'markers',
333
+ name: 'Class 1',
334
+ marker: { color: 'red', size: 10, symbol: 'circle' }
335
+ };
336
+
337
+ const testTrace = {
338
+ x: [testPoint[0]],
339
+ y: [testPoint[1]],
340
+ mode: 'markers',
341
+ name: 'Test Point',
342
+ marker: { color: 'green', size: 14, symbol: 'x' }
343
+ };
344
+
345
+ // Decision Boundary (Contour/Heatmap)
346
+ // The 'z' data comes from the backend, representing predictions on a grid
347
+ const boundaryTrace = {
348
+ z: data.decision_boundary_z,
349
+ x: data.decision_boundary_x_coords, // X coordinates of the grid
350
+ y: data.decision_boundary_y_coords, // Y coordinates of the grid
351
+ type: 'contour',
352
+ colorscale: [
353
+ ['0.0', 'rgba(0, 0, 255, 0.2)'], // Light blue for Class 0
354
+ ['1.0', 'rgba(255, 0, 0, 0.2)'] // Light red for Class 1
355
+ ],
356
+ showscale: false, // No color bar needed
357
+ hoverinfo: 'skip', // Don't show hover details for the boundary
358
+ opacity: 0.8 // Make it slightly transparent
359
+ };
360
+
361
+ // Plotly layout and redraw
362
+ Plotly.newPlot('plot', [boundaryTrace, trace0, trace1, testTrace], {
363
+ title: `Random Forest Decision Boundary`,
364
+ xaxis: { title: 'X1', range: [0, 9] }, // Adjust range based on your data
365
+ yaxis: { title: 'X2', range: [0, 9] }, // Adjust range
366
+ height: 500,
367
+ hovermode: 'closest'
368
+ }, {responsive: true}); // enable Plotly responsive config
369
+
370
+ // After plotting, call the resize helper to adapt sizes for current screen
371
+ adaptPlotForScreen();
372
+ }
373
+
374
+ // Helper to compute a reasonable plot height & marker sizes on small screens
375
+ function adaptPlotForScreen() {
376
+ // If plots are not initialized yet, skip
377
+ const plotEl = document.getElementById('plot');
378
+ const treeEl = document.getElementById('treeComparisonPlot');
379
+ if (!plotEl || !treeEl) return;
380
+
381
+ const w = window.innerWidth;
382
+ // Choose smaller height on narrow screens
383
+ const smallScreen = w <= 640;
384
+ const targetHeight = smallScreen ? 320 : 500;
385
+
386
+ // Update main plot height
387
+ Plotly.relayout('plot', {height: targetHeight});
388
+
389
+ // Also adjust marker sizes to better fit mobile (non-invasive)
390
+ // Find traces indices for markers: trace indices are [0=boundary,1=trace0,2=trace1,3=testTrace]
391
+ if (Plotly.d3 && Plotly.react) {
392
+ // change sizes via restyle
393
+ const classMarkerSize = smallScreen ? 7 : 10;
394
+ const testMarkerSize = smallScreen ? 10 : 14;
395
+ // restyle class0 (trace index 1) and class1 (2) sizes
396
+ Plotly.restyle('plot', {'marker.size': classMarkerSize}, [1]);
397
+ Plotly.restyle('plot', {'marker.size': classMarkerSize}, [2]);
398
+ Plotly.restyle('plot', {'marker.size': testMarkerSize}, [3]);
399
+ } else {
400
+ // fallback: try relayout only
401
+ Plotly.relayout('plot', {});
402
+ }
403
+
404
+ // For the tree comparison plot: adjust its layout height similarly
405
+ Plotly.relayout('treeComparisonPlot', {height: targetHeight});
406
+ // reduce marker sizes in treeComparisonPlot traces on small screens
407
+ const treeMarkerSize = smallScreen ? 18 : 30;
408
+ try {
409
+ // forest traces start at index 1..n — update all scatter traces
410
+ Plotly.restyle('treeComparisonPlot', {'marker.size': treeMarkerSize});
411
+ } catch (e) {
412
+ // ignore if restyle fails
413
+ console.warn("Could not restyle treeComparisonPlot markers:", e);
414
+ }
415
+ }
416
+
417
+ window.addEventListener('resize', function() {
418
+ // throttle slightly by using requestAnimationFrame for smoothness
419
+ if (window._rafResize) cancelAnimationFrame(window._rafResize);
420
+ window._rafResize = requestAnimationFrame(() => {
421
+ adaptPlotForScreen();
422
+ });
423
+ });
424
+
425
+ window.onload = () => {
426
+ // initial predict will create the main plot and call adaptPlotForScreen()
427
+ predict();
428
+
429
+ // Create the tree comparison plot (unchanged logic) but enable responsive config
430
+ const singleTreeTrace = {
431
+ type: "scatter",
432
+ mode: "markers+lines+text",
433
+ x: [2, 1, 3, 0.5, 1.5, 2.5, 3.5],
434
+ y: [3, 2, 2, 1, 1, 1, 1],
435
+ text: ["Root", "", "", "class 1", "class 1", "class 2", "class 2"],
436
+ textposition: "top center",
437
+ marker: { size: 30, color: "royalblue" },
438
+ line: { color: 'royalblue', width: 2 },
439
+ name: "Single Decision Tree",
440
+ showlegend: false,
441
+ xaxis: 'x1',
442
+ yaxis: 'y1'
443
+ };
444
+
445
+ const forestTraces = [
446
+ {
447
+ type: "scatter",
448
+ mode: "markers+lines+text",
449
+ x: [7, 6.5, 7.5],
450
+ y: [3, 2, 2],
451
+ text: ["Tree 1", "class 1", "class 1"],
452
+ textposition: "top center",
453
+ marker: { size: 28, color: "red" },
454
+ line: { color: 'red', width: 2 },
455
+ showlegend: false,
456
+ xaxis: 'x2',
457
+ yaxis: 'y2'
458
+ },
459
+ {
460
+ type: "scatter",
461
+ mode: "markers+lines+text",
462
+ x: [9, 8.5, 9.5],
463
+ y: [3, 2, 2],
464
+ text: ["Tree 2", "class 2", "class 2"],
465
+ textposition: "top center",
466
+ marker: { size: 28, color: "green" },
467
+ line: { color: 'green', width: 2 },
468
+ showlegend: false,
469
+ xaxis: 'x2',
470
+ yaxis: 'y2'
471
+ },
472
+ {
473
+ type: "scatter",
474
+ mode: "markers+lines+text",
475
+ x: [11, 10.5, 11.5],
476
+ y: [3, 2, 2],
477
+ text: ["Tree 3", "class 3", "class 3"],
478
+ textposition: "top center",
479
+ marker: { size: 28, color: "orange" },
480
+ line: { color: 'orange', width: 2 },
481
+ showlegend: false,
482
+ xaxis: 'x2',
483
+ yaxis: 'y2'
484
+ }
485
+ ];
486
+
487
+ const layout = {
488
+ grid: { rows: 1, columns: 2, pattern: 'independent' },
489
+ xaxis: {
490
+ domain: [0, 0.45],
491
+ title: { text: "Single Decision Tree", font: { size: 14 } },
492
+ showgrid: false,
493
+ zeroline: false
494
+ },
495
+ yaxis: {
496
+ domain: [0, 1],
497
+ showgrid: false,
498
+ zeroline: false
499
+ },
500
+ xaxis2: {
501
+ domain: [0.55, 1],
502
+ title: { text: "Random Forest (Multiple Trees)", font: { size: 14 } },
503
+ showgrid: false,
504
+ zeroline: false
505
+ },
506
+ yaxis2: {
507
+ domain: [0, 1],
508
+ showgrid: false,
509
+ zeroline: false
510
+ },
511
+ showlegend: false,
512
+ height: 500,
513
+ margin: { t: 30, b: 40 },
514
+ title: {
515
+ text: "📊 Visualizing Decision Tree vs Random Forest",
516
+ font: { size: 18 }
517
+ }
518
+ };
519
+
520
+ Plotly.newPlot('treeComparisonPlot', [singleTreeTrace, ...forestTraces], layout, {responsive: true});
521
+ // adapt its height/marker sizes immediately for current screen
522
+ adaptPlotForScreen();
523
+ }
524
+ </script>
525
+ <div class="mt-12 bg-white rounded-lg shadow-lg p-6 border border-gray-300">
526
+ <h2 class="text-2xl font-bold text-center text-purple-700 mb-4">🌳 Single Tree vs Random Forest</h2>
527
+ <div id="treeComparisonPlot" class="w-full" style="height: 500px;"></div>
528
  </div>
529
 
530
  <script>
531
+ // (No change here — the tree plot creation is moved into the onload above.)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  </script>
533
+ <!-- 📚 Theory Section -->
534
+ <div class="mt-8 text-gray-800 space-y-4">
535
+ <h3 class="text-xl font-bold text-blue-700">🔍 Working of Random Forest Algorithm</h3>
536
+ <ul class="list-disc list-inside space-y-2">
537
+ <li><strong>Create Many Decision Trees:</strong> The algorithm makes many decision trees using different random parts of the data.</li>
538
+ <li><strong>Pick Random Features:</strong> Each tree picks a random subset of features to make splits. This keeps trees diverse.</li>
539
+ <li><strong>Each Tree Makes a Prediction:</strong> Every tree gives its own output.</li>
540
+ <li><strong>Combine the Predictions:</strong>
541
+ <ul class="ml-6 list-disc">
542
+ <li><em>Classification:</em> Uses majority voting across trees.</li>
543
+ <li><em>Regression:</em> Averages the outputs of all trees.</li>
544
+ </ul>
545
+ </li>
546
+ <li><strong>Why It Works:</strong> Randomness prevents overfitting and improves overall prediction accuracy.</li>
547
+ </ul>
548
+
549
+ <h3 class="text-xl font-bold text-blue-700 mt-6">🌟 Key Features of Random Forest</h3>
550
+ <ul class="list-disc list-inside space-y-2">
551
+ <li><strong>Handles Missing Data:</strong> Works even with some missing values.</li>
552
+ <li><strong>Shows Feature Importance:</strong> Identifies most important features for prediction.</li>
553
+ <li><strong>Handles Complex Data:</strong> Efficient with large datasets and many features.</li>
554
+ <li><strong>Versatile:</strong> Works for both classification and regression tasks.</li>
555
+ </ul>
556
+
557
+ <h3 class="text-xl font-bold text-blue-700 mt-6">📌 Assumptions of Random Forest</h3>
558
+ <ul class="list-disc list-inside space-y-2">
559
+ <li>Each tree is independent and makes its own prediction.</li>
560
+ <li>Each tree is trained on random samples and features.</li>
561
+ <li>A large enough dataset is required for diverse learning.</li>
562
+ <li>Combining different trees improves accuracy.</li>
563
+ </ul>
564
+ </div>
565
  </div>
566
 
567
  </body>
568
  </html>
569
+ {% endblock %}