Sompote commited on
Commit
b4ffb5a
·
verified ·
1 Parent(s): 2d46bb9

Add 3 files

Browse files
Files changed (3) hide show
  1. README.md +7 -5
  2. index.html +970 -19
  3. prompts.txt +6 -0
README.md CHANGED
@@ -1,10 +1,12 @@
1
  ---
2
- title: Neural Network Demo
3
- emoji: 🏢
4
- colorFrom: gray
5
- colorTo: blue
6
  sdk: static
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: neural-network-demo
3
+ emoji: 🐳
4
+ colorFrom: purple
5
+ colorTo: red
6
  sdk: static
7
  pinned: false
8
+ tags:
9
+ - deepsite
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
index.html CHANGED
@@ -1,19 +1,970 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Neural Network Playground</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
9
+ <style>
10
+ .neuron {
11
+ transition: all 0.3s ease;
12
+ }
13
+ .neuron:hover {
14
+ transform: scale(1.1);
15
+ }
16
+ .connection {
17
+ stroke-dasharray: 1000;
18
+ stroke-dashoffset: 1000;
19
+ animation: dash 3s linear forwards;
20
+ }
21
+ @keyframes dash {
22
+ to {
23
+ stroke-dashoffset: 0;
24
+ }
25
+ }
26
+ .loss-chart {
27
+ height: 300px;
28
+ width: 100%;
29
+ }
30
+ .slide-in {
31
+ animation: slideIn 0.5s ease-out forwards;
32
+ }
33
+ @keyframes slideIn {
34
+ from {
35
+ transform: translateX(100%);
36
+ opacity: 0;
37
+ }
38
+ to {
39
+ transform: translateX(0);
40
+ opacity: 1;
41
+ }
42
+ }
43
+ .neuron-value {
44
+ font-size: 10px;
45
+ font-weight: bold;
46
+ text-anchor: middle;
47
+ }
48
+ .ground-truth-input {
49
+ background-color: #FEF3C7;
50
+ border: 1px solid #F59E0B;
51
+ }
52
+ .prediction-display {
53
+ background-color: #ECFDF5;
54
+ border: 1px solid #10B981;
55
+ }
56
+ .error-display {
57
+ background-color: #FEE2E2;
58
+ border: 1px solid #EF4444;
59
+ }
60
+ </style>
61
+ </head>
62
+ <body class="bg-gray-100 font-sans">
63
+ <div class="container mx-auto px-4 py-8">
64
+ <!-- Header -->
65
+ <header class="mb-10 text-center">
66
+ <h1 class="text-4xl md:text-5xl font-bold text-indigo-800 mb-4">Neural Network Playground</h1>
67
+ <p class="text-xl text-gray-600">4 Inputs to 1 Output Regression Model</p>
68
+ </header>
69
+
70
+ <!-- Main Content -->
71
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
72
+ <!-- Left Panel - Neural Network Visualization -->
73
+ <div class="lg:col-span-2 bg-white rounded-xl shadow-lg p-6">
74
+ <h2 class="text-2xl font-semibold text-indigo-700 mb-4">Interactive Neural Network</h2>
75
+
76
+ <!-- Network Controls -->
77
+ <div class="flex flex-wrap gap-4 mb-6">
78
+ <button id="initNetwork" class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg transition">
79
+ <i class="fas fa-network-wired mr-2"></i>Initialize Network
80
+ </button>
81
+ <button id="forwardPass" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition disabled:opacity-50" disabled>
82
+ <i class="fas fa-forward mr-2"></i>Forward Pass
83
+ </button>
84
+ <button id="backwardPass" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition disabled:opacity-50" disabled>
85
+ <i class="fas fa-backward mr-2"></i>Backward Pass
86
+ </button>
87
+ <button id="trainOneEpoch" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition disabled:opacity-50" disabled>
88
+ <i class="fas fa-cog mr-2"></i>Train One Epoch
89
+ </button>
90
+ <button id="trainNetwork" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg transition">
91
+ <i class="fas fa-cogs mr-2"></i>Train Network
92
+ </button>
93
+ </div>
94
+
95
+ <!-- Input Values Editor -->
96
+ <div class="mb-6 p-4 bg-gray-50 rounded-lg">
97
+ <h3 class="text-lg font-medium text-indigo-700 mb-3">Input Features</h3>
98
+ <div class="grid grid-cols-2 md:grid-cols-4 gap-4" id="inputValuesContainer">
99
+ <!-- Input values will be added here -->
100
+ </div>
101
+ </div>
102
+
103
+ <!-- Network Visualization -->
104
+ <div class="relative h-96 border-2 border-gray-200 rounded-lg p-4 flex items-center justify-center">
105
+ <svg id="networkCanvas" width="100%" height="100%" class="absolute inset-0"></svg>
106
+ <div id="networkPlaceholder" class="text-center text-gray-500">
107
+ <i class="fas fa-project-diagram text-5xl mb-4"></i>
108
+ <p>Click "Initialize Network" to begin</p>
109
+ </div>
110
+ </div>
111
+
112
+ <!-- Ground Truth and Output Values Display -->
113
+ <div class="mt-4 p-4 bg-gray-50 rounded-lg">
114
+ <h3 class="text-lg font-medium text-indigo-700 mb-3">Target & Prediction</h3>
115
+ <div class="grid grid-cols-1 gap-4" id="outputValuesContainer">
116
+ <!-- Output values will be added here -->
117
+ </div>
118
+ </div>
119
+
120
+ <!-- Loss Chart -->
121
+ <div class="mt-8">
122
+ <h3 class="text-xl font-medium text-indigo-700 mb-3">Training Loss</h3>
123
+ <div class="loss-chart bg-gray-50 rounded-lg p-4">
124
+ <canvas id="lossChart"></canvas>
125
+ </div>
126
+ </div>
127
+ </div>
128
+
129
+ <!-- Right Panel - Explanation -->
130
+ <div class="bg-white rounded-xl shadow-lg p-6">
131
+ <h2 class="text-2xl font-semibold text-indigo-700 mb-4">Learning Center</h2>
132
+
133
+ <!-- Tabs -->
134
+ <div class="flex border-b border-gray-200 mb-6">
135
+ <button class="tab-btn active px-4 py-2 font-medium text-indigo-600 border-b-2 border-indigo-600" data-tab="basics">Basics</button>
136
+ <button class="tab-btn px-4 py-2 font-medium text-gray-500 hover:text-indigo-600" data-tab="backprop">Backpropagation</button>
137
+ <button class="tab-btn px-4 py-2 font-medium text-gray-500 hover:text-indigo-600" data-tab="loss">Loss Function</button>
138
+ </div>
139
+
140
+ <!-- Tab Content -->
141
+ <div id="basics" class="tab-content slide-in">
142
+ <h3 class="text-lg font-semibold mb-3">Regression Model</h3>
143
+ <p class="mb-4 text-gray-700">This neural network takes 4 input features and predicts a single continuous output value. It's designed for regression tasks where we want to predict a numerical value based on multiple input features.</p>
144
+
145
+ <div class="bg-indigo-50 p-4 rounded-lg mb-4">
146
+ <h4 class="font-medium text-indigo-700 mb-2"><i class="fas fa-lightbulb mr-2"></i>Model Architecture:</h4>
147
+ <ul class="list-disc pl-5 space-y-1 text-gray-700">
148
+ <li><strong>Input Layer:</strong> 4 neurons (one for each feature)</li>
149
+ <li><strong>Hidden Layer:</strong> 4 neurons with activation</li>
150
+ <li><strong>Output Layer:</strong> 1 neuron (linear activation for regression)</li>
151
+ </ul>
152
+ </div>
153
+
154
+ <p class="text-gray-700">Adjust the input sliders and set your target value to see how the network learns to minimize the difference between its prediction and the target.</p>
155
+ </div>
156
+
157
+ <div id="backprop" class="tab-content hidden">
158
+ <h3 class="text-lg font-semibold mb-3">Backpropagation Explained</h3>
159
+ <p class="mb-4 text-gray-700">Backpropagation calculates how much each weight contributes to the error and adjusts them to reduce the difference between the predicted output and the target value.</p>
160
+
161
+ <div class="bg-green-50 p-4 rounded-lg mb-4">
162
+ <h4 class="font-medium text-green-700 mb-2"><i class="fas fa-random mr-2"></i>Training Process:</h4>
163
+ <ol class="list-decimal pl-5 space-y-1 text-gray-700">
164
+ <li>Forward pass computes the prediction</li>
165
+ <li>Compare prediction with target value</li>
166
+ <li>Calculate Mean Squared Error (MSE)</li>
167
+ <li>Backpropagate error through the network</li>
168
+ <li>Update weights using gradient descent</li>
169
+ <li>Repeat until error is minimized</li>
170
+ </ol>
171
+ </div>
172
+
173
+ <p class="text-gray-700">Click "Forward Pass" then "Backward Pass" to see this in action!</p>
174
+ </div>
175
+
176
+ <div id="loss" class="tab-content hidden">
177
+ <h3 class="text-lg font-semibold mb-3">Loss Functions</h3>
178
+ <p class="mb-4 text-gray-700">For regression problems, we typically use Mean Squared Error (MSE) to measure how far our predictions are from the target values.</p>
179
+
180
+ <div class="bg-purple-50 p-4 rounded-lg mb-4">
181
+ <h4 class="font-medium text-purple-700 mb-2"><i class="fas fa-chart-line mr-2"></i>Mean Squared Error:</h4>
182
+ <p class="text-gray-700">MSE = 1/n Σ(y_true - y_pred)²</p>
183
+ <p class="text-gray-700 mt-2">Where:</p>
184
+ <ul class="list-disc pl-5 space-y-1 text-gray-700">
185
+ <li>y_true = target value</li>
186
+ <li>y_pred = predicted value</li>
187
+ <li>n = number of samples (1 in our case)</li>
188
+ </ul>
189
+ </div>
190
+
191
+ <div class="bg-yellow-50 p-4 rounded-lg">
192
+ <h4 class="font-medium text-yellow-700 mb-2"><i class="fas fa-bullseye mr-2"></i>Why Minimize MSE?</h4>
193
+ <p class="text-gray-700">MSE gives higher weight to larger errors, which makes it sensitive to outliers but effective for most regression problems. The training process adjusts weights to gradually reduce MSE.</p>
194
+ </div>
195
+ </div>
196
+
197
+ <!-- Interactive Console -->
198
+ <div class="mt-8">
199
+ <h3 class="text-xl font-medium text-indigo-700 mb-3">Network Console</h3>
200
+ <div class="bg-gray-800 text-green-400 p-4 rounded-lg font-mono text-sm h-40 overflow-y-auto" id="console">
201
+ <div>> Welcome to Neural Network Playground!</div>
202
+ <div>> Click "Initialize Network" to begin.</div>
203
+ </div>
204
+ </div>
205
+ </div>
206
+ </div>
207
+
208
+ <!-- Training Parameters -->
209
+ <div class="mt-10 bg-white rounded-xl shadow-lg p-6">
210
+ <h2 class="text-2xl font-semibold text-indigo-700 mb-4">Training Parameters</h2>
211
+
212
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
213
+ <div>
214
+ <label class="block text-gray-700 mb-2">Learning Rate</label>
215
+ <input type="range" id="learningRate" min="0.001" max="1" step="0.001" value="0.1" class="w-full">
216
+ <div class="text-right text-gray-600"><span id="lrValue">0.1</span></div>
217
+ </div>
218
+
219
+ <div>
220
+ <label class="block text-gray-700 mb-2">Epochs</label>
221
+ <input type="range" id="epochs" min="1" max="100" step="1" value="10" class="w-full">
222
+ <div class="text-right text-gray-600"><span id="epochValue">10</span></div>
223
+ </div>
224
+
225
+ <div>
226
+ <label class="block text-gray-700 mb-2">Batch Size</label>
227
+ <select id="batchSize" class="w-full p-2 border border-gray-300 rounded">
228
+ <option value="1">1 (Stochastic)</option>
229
+ <option value="10" selected>10 (Mini-batch)</option>
230
+ <option value="100">100 (Batch)</option>
231
+ </select>
232
+ </div>
233
+ </div>
234
+
235
+ <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
236
+ <div>
237
+ <label class="block text-gray-700 mb-2">Hidden Layer Activation</label>
238
+ <select id="activation" class="w-full p-2 border border-gray-300 rounded">
239
+ <option value="sigmoid">Sigmoid</option>
240
+ <option value="relu">ReLU</option>
241
+ <option value="tanh">Tanh</option>
242
+ </select>
243
+ </div>
244
+
245
+ <div>
246
+ <label class="block text-gray-700 mb-2">Loss Function</label>
247
+ <select id="lossFunction" class="w-full p-2 border border-gray-300 rounded">
248
+ <option value="mse" selected>Mean Squared Error</option>
249
+ <option value="mae">Mean Absolute Error</option>
250
+ </select>
251
+ </div>
252
+ </div>
253
+ </div>
254
+ </div>
255
+
256
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
257
+ <script>
258
+ // DOM Elements
259
+ const initNetworkBtn = document.getElementById('initNetwork');
260
+ const forwardPassBtn = document.getElementById('forwardPass');
261
+ const backwardPassBtn = document.getElementById('backwardPass');
262
+ const trainOneEpochBtn = document.getElementById('trainOneEpoch');
263
+ const trainNetworkBtn = document.getElementById('trainNetwork');
264
+ const networkCanvas = document.getElementById('networkCanvas');
265
+ const networkPlaceholder = document.getElementById('networkPlaceholder');
266
+ const consoleOutput = document.getElementById('console');
267
+ const tabButtons = document.querySelectorAll('.tab-btn');
268
+ const tabContents = document.querySelectorAll('.tab-content');
269
+ const inputValuesContainer = document.getElementById('inputValuesContainer');
270
+ const outputValuesContainer = document.getElementById('outputValuesContainer');
271
+
272
+ // Parameters
273
+ const learningRate = document.getElementById('learningRate');
274
+ const lrValue = document.getElementById('lrValue');
275
+ const epochs = document.getElementById('epochs');
276
+ const epochValue = document.getElementById('epochValue');
277
+
278
+ // Neural Network State
279
+ let networkInitialized = false;
280
+ let inputValues = [0.5, 0.3, 0.8, 0.2]; // 4 input values
281
+ let outputValue = 0; // Single output value
282
+ let hiddenValues = [0, 0, 0, 0];
283
+ let groundTruthValue = 0.5; // Default ground truth value
284
+
285
+ // Network weights and biases
286
+ let weightsInputHidden = [];
287
+ let weightsHiddenOutput = [];
288
+ let biasHidden = 0.1;
289
+ let biasOutput = 0.1;
290
+
291
+ // Chart setup
292
+ const lossChartCtx = document.getElementById('lossChart').getContext('2d');
293
+ let lossChart = new Chart(lossChartCtx, {
294
+ type: 'line',
295
+ data: {
296
+ labels: [],
297
+ datasets: [{
298
+ label: 'Training Loss (MSE)',
299
+ data: [],
300
+ borderColor: 'rgb(99, 102, 241)',
301
+ tension: 0.1,
302
+ fill: false
303
+ }]
304
+ },
305
+ options: {
306
+ responsive: true,
307
+ scales: {
308
+ y: {
309
+ beginAtZero: true,
310
+ title: {
311
+ display: true,
312
+ text: 'Loss Value'
313
+ }
314
+ },
315
+ x: {
316
+ title: {
317
+ display: true,
318
+ text: 'Epoch'
319
+ }
320
+ }
321
+ }
322
+ }
323
+ });
324
+
325
+ // Event Listeners
326
+ learningRate.addEventListener('input', () => {
327
+ lrValue.textContent = learningRate.value;
328
+ });
329
+
330
+ epochs.addEventListener('input', () => {
331
+ epochValue.textContent = epochs.value;
332
+ });
333
+
334
+ tabButtons.forEach(button => {
335
+ button.addEventListener('click', () => {
336
+ const tabId = button.getAttribute('data-tab');
337
+
338
+ // Update active tab
339
+ tabButtons.forEach(btn => {
340
+ btn.classList.remove('text-indigo-600', 'border-indigo-600');
341
+ btn.classList.add('text-gray-500', 'hover:text-indigo-600');
342
+ });
343
+ button.classList.add('text-indigo-600', 'border-indigo-600');
344
+ button.classList.remove('text-gray-500', 'hover:text-indigo-600');
345
+
346
+ // Show selected content
347
+ tabContents.forEach(content => {
348
+ content.classList.add('hidden');
349
+ if (content.id === tabId) {
350
+ content.classList.remove('hidden');
351
+ content.classList.add('slide-in');
352
+ }
353
+ });
354
+ });
355
+ });
356
+
357
+ // Neural Network Simulation
358
+ initNetworkBtn.addEventListener('click', () => {
359
+ logToConsole("Initializing neural network with 4 inputs and 1 output...");
360
+
361
+ // Clear previous network
362
+ networkCanvas.innerHTML = '';
363
+ networkPlaceholder.classList.add('hidden');
364
+
365
+ // Initialize input values
366
+ inputValues = [0.5, 0.3, 0.8, 0.2];
367
+ createInputControls();
368
+
369
+ // Initialize output and ground truth values
370
+ outputValue = 0;
371
+ groundTruthValue = 0.5;
372
+ updateOutputDisplay();
373
+
374
+ // Initialize weights with random values
375
+ initializeWeights();
376
+
377
+ // Draw network
378
+ drawNeuralNetwork();
379
+
380
+ networkInitialized = true;
381
+ forwardPassBtn.disabled = false;
382
+ backwardPassBtn.disabled = true;
383
+ trainOneEpochBtn.disabled = false;
384
+
385
+ logToConsole("Network initialized! Click 'Forward Pass' to see data flow.");
386
+ });
387
+
388
+ forwardPassBtn.addEventListener('click', () => {
389
+ if (!networkInitialized) return;
390
+
391
+ logToConsole("Performing forward pass...");
392
+
393
+ // Simulate forward pass with current input values
394
+ simulateForwardPass();
395
+ animateForwardPass();
396
+
397
+ backwardPassBtn.disabled = false;
398
+ logToConsole("Forward pass complete! Now click 'Backward Pass' to see backpropagation.");
399
+ });
400
+
401
+ backwardPassBtn.addEventListener('click', () => {
402
+ if (!networkInitialized) return;
403
+
404
+ logToConsole("Performing backward pass (backpropagation)...");
405
+ performBackwardPass();
406
+ animateBackwardPass();
407
+
408
+ logToConsole("Backward pass complete! Weights updated. Try training to see loss reduction.");
409
+ });
410
+
411
+ trainOneEpochBtn.addEventListener('click', () => {
412
+ if (!networkInitialized) {
413
+ logToConsole("Please initialize network first!");
414
+ return;
415
+ }
416
+
417
+ const lr = parseFloat(learningRate.value);
418
+
419
+ logToConsole(`Training for 1 epoch with learning rate ${lr}...`);
420
+
421
+ // Perform one training epoch
422
+ trainOneEpoch(lr);
423
+ });
424
+
425
+ trainNetworkBtn.addEventListener('click', () => {
426
+ if (!networkInitialized) {
427
+ logToConsole("Please initialize network first!");
428
+ return;
429
+ }
430
+
431
+ const numEpochs = parseInt(epochs.value);
432
+ const lr = parseFloat(learningRate.value);
433
+
434
+ logToConsole(`Starting training for ${numEpochs} epochs with learning rate ${lr}...`);
435
+
436
+ // Simulate training
437
+ simulateTraining(numEpochs, lr);
438
+ });
439
+
440
+ // Helper Functions
441
+ function logToConsole(message) {
442
+ const newLine = document.createElement('div');
443
+ newLine.textContent = `> ${message}`;
444
+ consoleOutput.appendChild(newLine);
445
+ consoleOutput.scrollTop = consoleOutput.scrollHeight;
446
+ }
447
+
448
+ function initializeWeights() {
449
+ // Initialize weights between input and hidden layer (4x4)
450
+ weightsInputHidden = [];
451
+ for (let i = 0; i < 4; i++) {
452
+ weightsInputHidden[i] = [];
453
+ for (let j = 0; j < 4; j++) {
454
+ weightsInputHidden[i][j] = 0.3 + Math.random() * 0.4; // Random weights between 0.3 and 0.7
455
+ }
456
+ }
457
+
458
+ // Initialize weights between hidden and output layer (4x1)
459
+ weightsHiddenOutput = [];
460
+ for (let i = 0; i < 4; i++) {
461
+ weightsHiddenOutput[i] = 0.3 + Math.random() * 0.4; // Random weights between 0.3 and 0.7
462
+ }
463
+
464
+ // Initialize biases
465
+ biasHidden = 0.1;
466
+ biasOutput = 0.1;
467
+ }
468
+
469
+ function createInputControls() {
470
+ inputValuesContainer.innerHTML = '';
471
+ inputValues.forEach((value, index) => {
472
+ const inputGroup = document.createElement('div');
473
+ inputGroup.className = 'flex flex-col';
474
+
475
+ const label = document.createElement('label');
476
+ label.className = 'text-sm font-medium text-gray-700 mb-1';
477
+ label.textContent = `Feature ${index + 1}`;
478
+
479
+ const input = document.createElement('input');
480
+ input.type = 'range';
481
+ input.min = '0';
482
+ input.max = '1';
483
+ input.step = '0.01';
484
+ input.value = value;
485
+ input.className = 'w-full';
486
+ input.dataset.index = index;
487
+
488
+ const valueDisplay = document.createElement('div');
489
+ valueDisplay.className = 'text-right text-sm text-gray-600';
490
+ valueDisplay.textContent = value.toFixed(2);
491
+
492
+ input.addEventListener('input', (e) => {
493
+ const newValue = parseFloat(e.target.value);
494
+ inputValues[index] = newValue;
495
+ valueDisplay.textContent = newValue.toFixed(2);
496
+
497
+ // Update the neuron value display
498
+ const neuronValue = document.getElementById(`neuron-value-0-${index}`);
499
+ if (neuronValue) {
500
+ neuronValue.textContent = newValue.toFixed(2);
501
+ }
502
+ });
503
+
504
+ inputGroup.appendChild(label);
505
+ inputGroup.appendChild(input);
506
+ inputGroup.appendChild(valueDisplay);
507
+ inputValuesContainer.appendChild(inputGroup);
508
+ });
509
+ }
510
+
511
+ function updateOutputDisplay() {
512
+ outputValuesContainer.innerHTML = '';
513
+ const outputGroup = document.createElement('div');
514
+ outputGroup.className = 'flex flex-col space-y-2';
515
+
516
+ // Ground Truth Input
517
+ const gtLabel = document.createElement('label');
518
+ gtLabel.className = 'text-sm font-medium text-gray-700';
519
+ gtLabel.textContent = `Target Value`;
520
+
521
+ const gtInput = document.createElement('input');
522
+ gtInput.type = 'range';
523
+ gtInput.min = '0';
524
+ gtInput.max = '1';
525
+ gtInput.step = '0.01';
526
+ gtInput.value = groundTruthValue;
527
+ gtInput.className = 'w-full ground-truth-input';
528
+
529
+ const gtValueDisplay = document.createElement('div');
530
+ gtValueDisplay.className = 'text-right text-sm text-gray-600';
531
+ gtValueDisplay.textContent = groundTruthValue.toFixed(2);
532
+
533
+ gtInput.addEventListener('input', (e) => {
534
+ const newValue = parseFloat(e.target.value);
535
+ groundTruthValue = newValue;
536
+ gtValueDisplay.textContent = newValue.toFixed(2);
537
+ logToConsole(`Updated target value to ${newValue.toFixed(2)}`);
538
+ });
539
+
540
+ // Prediction Display
541
+ const predLabel = document.createElement('label');
542
+ predLabel.className = 'text-sm font-medium text-gray-700 mt-2';
543
+ predLabel.textContent = `Prediction`;
544
+
545
+ const predDisplay = document.createElement('div');
546
+ predDisplay.className = 'p-2 rounded prediction-display text-sm';
547
+ predDisplay.textContent = outputValue.toFixed(4);
548
+
549
+ // Error Display
550
+ const errorLabel = document.createElement('label');
551
+ errorLabel.className = 'text-sm font-medium text-gray-700 mt-2';
552
+ errorLabel.textContent = `Error (MSE)`;
553
+
554
+ const errorDisplay = document.createElement('div');
555
+ errorDisplay.className = 'p-2 rounded error-display text-sm';
556
+ const error = Math.pow(outputValue - groundTruthValue, 2);
557
+ errorDisplay.textContent = error.toFixed(4);
558
+
559
+ outputGroup.appendChild(gtLabel);
560
+ outputGroup.appendChild(gtInput);
561
+ outputGroup.appendChild(gtValueDisplay);
562
+ outputGroup.appendChild(predLabel);
563
+ outputGroup.appendChild(predDisplay);
564
+ outputGroup.appendChild(errorLabel);
565
+ outputGroup.appendChild(errorDisplay);
566
+
567
+ outputValuesContainer.appendChild(outputGroup);
568
+
569
+ // Update the neuron value display
570
+ const neuronValue = document.getElementById(`neuron-value-2-0`);
571
+ if (neuronValue) {
572
+ neuronValue.textContent = outputValue.toFixed(2);
573
+ }
574
+ }
575
+
576
+ function drawNeuralNetwork() {
577
+ const svg = networkCanvas;
578
+ const width = svg.clientWidth;
579
+ const height = svg.clientHeight;
580
+
581
+ // Define layers
582
+ const layers = [
583
+ { name: "Input", neurons: 4, x: width * 0.2 },
584
+ { name: "Hidden", neurons: 4, x: width * 0.5 },
585
+ { name: "Output", neurons: 1, x: width * 0.8 }
586
+ ];
587
+
588
+ // Draw connections first (so they're behind neurons)
589
+ for (let i = 0; i < layers.length - 1; i++) {
590
+ const currentLayer = layers[i];
591
+ const nextLayer = layers[i + 1];
592
+
593
+ for (let j = 0; j < currentLayer.neurons; j++) {
594
+ for (let k = 0; k < nextLayer.neurons; k++) {
595
+ const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
596
+ line.setAttribute("x1", currentLayer.x);
597
+ line.setAttribute("y1", height * (j + 1) / (currentLayer.neurons + 1));
598
+ line.setAttribute("x2", nextLayer.x);
599
+ line.setAttribute("y2", height * (k + 1) / (nextLayer.neurons + 1));
600
+ line.setAttribute("stroke", "#9CA3AF");
601
+ line.setAttribute("stroke-width", "2");
602
+ line.setAttribute("class", "connection");
603
+ line.setAttribute("id", `conn-${i}-${j}-${k}`);
604
+ svg.appendChild(line);
605
+ }
606
+ }
607
+ }
608
+
609
+ // Draw neurons
610
+ layers.forEach((layer, layerIndex) => {
611
+ for (let i = 0; i < layer.neurons; i++) {
612
+ const yPos = height * (i + 1) / (layer.neurons + 1);
613
+
614
+ // Draw neuron
615
+ const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
616
+ circle.setAttribute("cx", layer.x);
617
+ circle.setAttribute("cy", yPos);
618
+ circle.setAttribute("r", 20);
619
+ circle.setAttribute("fill", layerIndex === 0 ? "#4F46E5" : layerIndex === 1 ? "#10B981" : "#EC4899");
620
+ circle.setAttribute("class", "neuron");
621
+ circle.setAttribute("id", `neuron-${layerIndex}-${i}`);
622
+ svg.appendChild(circle);
623
+
624
+ // Add neuron label
625
+ const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
626
+ text.setAttribute("x", layer.x);
627
+ text.setAttribute("y", yPos + 5);
628
+ text.setAttribute("text-anchor", "middle");
629
+ text.setAttribute("fill", "white");
630
+ text.setAttribute("font-size", "12");
631
+ text.textContent = i + 1;
632
+ svg.appendChild(text);
633
+
634
+ // Add neuron value display
635
+ const valueText = document.createElementNS("http://www.w3.org/2000/svg", "text");
636
+ valueText.setAttribute("x", layer.x);
637
+ valueText.setAttribute("y", yPos + 25);
638
+ valueText.setAttribute("text-anchor", "middle");
639
+ valueText.setAttribute("fill", "#6B7280");
640
+ valueText.setAttribute("class", "neuron-value");
641
+ valueText.setAttribute("id", `neuron-value-${layerIndex}-${i}`);
642
+
643
+ // Set initial values
644
+ if (layerIndex === 0) {
645
+ valueText.textContent = inputValues[i] ? inputValues[i].toFixed(2) : "0.00";
646
+ } else if (layerIndex === 2) {
647
+ valueText.textContent = outputValue ? outputValue.toFixed(2) : "0.00";
648
+ } else {
649
+ valueText.textContent = "0.00";
650
+ }
651
+
652
+ svg.appendChild(valueText);
653
+
654
+ // Add layer label for first neuron
655
+ if (i === 0) {
656
+ const layerText = document.createElementNS("http://www.w3.org/2000/svg", "text");
657
+ layerText.setAttribute("x", layer.x);
658
+ layerText.setAttribute("y", 20);
659
+ layerText.setAttribute("text-anchor", "middle");
660
+ layerText.setAttribute("fill", "#6B7280");
661
+ layerText.setAttribute("font-size", "14");
662
+ layerText.setAttribute("font-weight", "bold");
663
+ layerText.textContent = layer.name + " Layer";
664
+ svg.appendChild(layerText);
665
+ }
666
+ }
667
+ });
668
+ }
669
+
670
+ function simulateForwardPass() {
671
+ const activation = document.getElementById('activation').value;
672
+
673
+ // Calculate hidden layer values
674
+ hiddenValues = [];
675
+ for (let i = 0; i < 4; i++) {
676
+ let sum = 0;
677
+ for (let j = 0; j < 4; j++) {
678
+ sum += inputValues[j] * weightsInputHidden[j][i];
679
+ }
680
+ sum += biasHidden;
681
+
682
+ // Apply activation
683
+ hiddenValues[i] = applyActivation(sum, activation);
684
+
685
+ // Update hidden layer display
686
+ const neuronValue = document.getElementById(`neuron-value-1-${i}`);
687
+ if (neuronValue) {
688
+ neuronValue.textContent = hiddenValues[i].toFixed(2);
689
+ }
690
+ }
691
+
692
+ // Calculate output value (linear activation for regression)
693
+ let sum = 0;
694
+ for (let j = 0; j < 4; j++) {
695
+ sum += hiddenValues[j] * weightsHiddenOutput[j];
696
+ }
697
+ sum += biasOutput;
698
+ outputValue = sum; // No activation for output in regression
699
+
700
+ updateOutputDisplay();
701
+ }
702
+
703
+ function applyActivation(x, activation) {
704
+ switch (activation) {
705
+ case 'relu':
706
+ return Math.max(0, x);
707
+ case 'sigmoid':
708
+ return 1 / (1 + Math.exp(-x));
709
+ case 'tanh':
710
+ return Math.tanh(x);
711
+ default:
712
+ return x;
713
+ }
714
+ }
715
+
716
+ function applyActivationDerivative(x, activation) {
717
+ switch (activation) {
718
+ case 'relu':
719
+ return x > 0 ? 1 : 0;
720
+ case 'sigmoid':
721
+ const sig = 1 / (1 + Math.exp(-x));
722
+ return sig * (1 - sig);
723
+ case 'tanh':
724
+ return 1 - Math.pow(Math.tanh(x), 2);
725
+ default:
726
+ return 1;
727
+ }
728
+ }
729
+
730
+ function performBackwardPass() {
731
+ const lr = parseFloat(learningRate.value);
732
+ const activation = document.getElementById('activation').value;
733
+
734
+ // Calculate output error (dE/dy)
735
+ const outputError = outputValue - groundTruthValue;
736
+
737
+ // Calculate gradients for hidden-output weights
738
+ const hiddenOutputGradients = [];
739
+ for (let i = 0; i < 4; i++) {
740
+ hiddenOutputGradients[i] = outputError * hiddenValues[i];
741
+ }
742
+
743
+ // Calculate hidden layer errors (dE/dh)
744
+ const hiddenErrors = [];
745
+ for (let i = 0; i < 4; i++) {
746
+ hiddenErrors[i] = outputError * weightsHiddenOutput[i] * applyActivationDerivative(hiddenValues[i], activation);
747
+ }
748
+
749
+ // Calculate gradients for input-hidden weights
750
+ const inputHiddenGradients = [];
751
+ for (let i = 0; i < 4; i++) {
752
+ inputHiddenGradients[i] = [];
753
+ for (let j = 0; j < 4; j++) {
754
+ inputHiddenGradients[i][j] = hiddenErrors[j] * inputValues[i];
755
+ }
756
+ }
757
+
758
+ // Update weights
759
+ for (let i = 0; i < 4; i++) {
760
+ for (let j = 0; j < 4; j++) {
761
+ weightsInputHidden[i][j] -= lr * inputHiddenGradients[i][j];
762
+ }
763
+ }
764
+
765
+ for (let i = 0; i < 4; i++) {
766
+ weightsHiddenOutput[i] -= lr * hiddenOutputGradients[i];
767
+ }
768
+
769
+ // Update biases
770
+ biasHidden -= lr * hiddenErrors.reduce((sum, err) => sum + err, 0);
771
+ biasOutput -= lr * outputError;
772
+
773
+ logToConsole(`Weights updated with learning rate ${lr}. Loss: ${calculateLoss().toFixed(4)}`);
774
+ }
775
+
776
+ function trainOneEpoch(learningRate) {
777
+ // Perform forward pass
778
+ simulateForwardPass();
779
+
780
+ // Perform backward pass
781
+ performBackwardPass();
782
+
783
+ // Update chart
784
+ lossChart.data.labels.push(`Epoch ${lossChart.data.labels.length + 1}`);
785
+ lossChart.data.datasets[0].data.push(calculateLoss());
786
+ lossChart.update();
787
+
788
+ logToConsole(`1 epoch complete! Current loss: ${calculateLoss().toFixed(4)}`);
789
+ }
790
+
791
+ function animateForwardPass() {
792
+ const svg = networkCanvas;
793
+
794
+ // Animate connections from input to hidden
795
+ setTimeout(() => {
796
+ for (let i = 0; i < 4; i++) {
797
+ for (let j = 0; j < 4; j++) {
798
+ const conn = document.getElementById(`conn-0-${i}-${j}`);
799
+ conn.setAttribute("stroke", "#4F46E5");
800
+ conn.setAttribute("stroke-width", "3");
801
+
802
+ // Highlight neurons
803
+ document.getElementById(`neuron-0-${i}`).setAttribute("fill", "#6366F1");
804
+ document.getElementById(`neuron-1-${j}`).setAttribute("fill", "#34D399");
805
+ }
806
+ }
807
+ }, 500);
808
+
809
+ // Animate connections from hidden to output
810
+ setTimeout(() => {
811
+ for (let i = 0; i < 4; i++) {
812
+ for (let j = 0; j < 1; j++) {
813
+ const conn = document.getElementById(`conn-1-${i}-${j}`);
814
+ conn.setAttribute("stroke", "#EC4899");
815
+ conn.setAttribute("stroke-width", "3");
816
+
817
+ // Highlight neurons
818
+ document.getElementById(`neuron-1-${i}`).setAttribute("fill", "#10B981");
819
+ document.getElementById(`neuron-2-${j}`).setAttribute("fill", "#F472B6");
820
+ }
821
+ }
822
+ }, 1500);
823
+
824
+ // Reset colors after animation
825
+ setTimeout(() => {
826
+ const connections = svg.querySelectorAll("line");
827
+ connections.forEach(conn => {
828
+ conn.setAttribute("stroke", "#9CA3AF");
829
+ conn.setAttribute("stroke-width", "2");
830
+ });
831
+
832
+ // Reset neuron colors
833
+ for (let i = 0; i < 4; i++) {
834
+ document.getElementById(`neuron-0-${i}`).setAttribute("fill", "#4F46E5");
835
+ }
836
+ for (let i = 0; i < 4; i++) {
837
+ document.getElementById(`neuron-1-${i}`).setAttribute("fill", "#10B981");
838
+ }
839
+ document.getElementById(`neuron-2-0`).setAttribute("fill", "#EC4899");
840
+ }, 3000);
841
+ }
842
+
843
+ function animateBackwardPass() {
844
+ const svg = networkCanvas;
845
+
846
+ // Animate connections from output to hidden (reverse direction)
847
+ setTimeout(() => {
848
+ for (let i = 0; i < 1; i++) {
849
+ for (let j = 0; j < 4; j++) {
850
+ const conn = document.getElementById(`conn-1-${j}-${i}`);
851
+ conn.setAttribute("stroke", "#F59E0B");
852
+ conn.setAttribute("stroke-width", "3");
853
+
854
+ // Highlight neurons
855
+ document.getElementById(`neuron-2-${i}`).setAttribute("fill", "#F472B6");
856
+ document.getElementById(`neuron-1-${j}`).setAttribute("fill", "#34D399");
857
+ }
858
+ }
859
+ }, 500);
860
+
861
+ // Animate connections from hidden to input (reverse direction)
862
+ setTimeout(() => {
863
+ for (let i = 0; i < 4; i++) {
864
+ for (let j = 0; j < 4; j++) {
865
+ const conn = document.getElementById(`conn-0-${j}-${i}`);
866
+ conn.setAttribute("stroke", "#F59E0B");
867
+ conn.setAttribute("stroke-width", "3");
868
+
869
+ // Highlight neurons
870
+ document.getElementById(`neuron-1-${i}`).setAttribute("fill", "#10B981");
871
+ document.getElementById(`neuron-0-${j}`).setAttribute("fill", "#6366F1");
872
+ }
873
+ }
874
+ }, 1500);
875
+
876
+ // Show weight updates
877
+ setTimeout(() => {
878
+ logToConsole("Calculating gradients and updating weights...");
879
+
880
+ // Calculate loss based on ground truth value
881
+ const loss = calculateLoss();
882
+ logToConsole(`Current loss: ${loss.toFixed(4)} (based on target value)`);
883
+
884
+ // Simulate weight updates by slightly changing connection thickness
885
+ const connections = svg.querySelectorAll("line");
886
+ connections.forEach(conn => {
887
+ const currentWidth = parseFloat(conn.getAttribute("stroke-width"));
888
+ const newWidth = Math.max(1, currentWidth + (Math.random() - 0.5) * 0.5);
889
+ conn.setAttribute("stroke-width", newWidth.toString());
890
+ });
891
+ }, 2500);
892
+
893
+ // Reset colors after animation
894
+ setTimeout(() => {
895
+ const connections = svg.querySelectorAll("line");
896
+ connections.forEach(conn => {
897
+ conn.setAttribute("stroke", "#9CA3AF");
898
+ conn.setAttribute("stroke-width", "2");
899
+ });
900
+
901
+ // Reset neuron colors
902
+ for (let i = 0; i < 4; i++) {
903
+ document.getElementById(`neuron-0-${i}`).setAttribute("fill", "#4F46E5");
904
+ }
905
+ for (let i = 0; i < 4; i++) {
906
+ document.getElementById(`neuron-1-${i}`).setAttribute("fill", "#10B981");
907
+ }
908
+ document.getElementById(`neuron-2-0`).setAttribute("fill", "#EC4899");
909
+
910
+ logToConsole("Backpropagation complete! Weights updated based on error gradients.");
911
+ }, 4000);
912
+ }
913
+
914
+ function simulateTraining(epochs, learningRate) {
915
+ // Clear previous chart data
916
+ lossChart.data.labels = [];
917
+ lossChart.data.datasets[0].data = [];
918
+
919
+ // Generate simulated loss values based on ground truth
920
+ const initialLoss = calculateLoss();
921
+ let currentLoss = initialLoss;
922
+
923
+ for (let epoch = 1; epoch <= epochs; epoch++) {
924
+ // Perform actual training (forward + backward pass)
925
+ simulateForwardPass();
926
+ performBackwardPass();
927
+
928
+ // Calculate new loss
929
+ currentLoss = calculateLoss();
930
+
931
+ // Add to chart
932
+ lossChart.data.labels.push(`Epoch ${epoch}`);
933
+ lossChart.data.datasets[0].data.push(currentLoss);
934
+
935
+ // Update console
936
+ setTimeout(() => {
937
+ logToConsole(`Epoch ${epoch}/${epochs} - Loss: ${currentLoss.toFixed(4)}`);
938
+
939
+ // Animate the network occasionally
940
+ if (epoch % 3 === 0) {
941
+ animateForwardPass();
942
+ setTimeout(() => animateBackwardPass(), 2000);
943
+ }
944
+ }, epoch * 800);
945
+ }
946
+
947
+ // Update chart
948
+ setTimeout(() => {
949
+ lossChart.update();
950
+ logToConsole(`Training complete! Final loss: ${currentLoss.toFixed(4)}`);
951
+ }, epochs * 800 + 500);
952
+ }
953
+
954
+ function calculateLoss() {
955
+ const lossFunction = document.getElementById('lossFunction').value;
956
+ let loss = 0;
957
+
958
+ if (lossFunction === 'mse') {
959
+ // Mean Squared Error
960
+ loss = Math.pow(outputValue - groundTruthValue, 2);
961
+ } else {
962
+ // Mean Absolute Error
963
+ loss = Math.abs(outputValue - groundTruthValue);
964
+ }
965
+
966
+ return loss;
967
+ }
968
+ </script>
969
+ <p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Sompote/neural-network-demo" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
970
+ </html>
prompts.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ make track app to teach about neural network to reduce loss by back propagation
2
+ show input value and output value and let user chan change
3
+ let user to set the ground truth value
4
+ change to be 4 inputs and single output
5
+ when I click initialize network it not start please check
6
+ The loss is not reduce plate check back propagation code and add backpropagaion button to do it for one epoch