-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathultra_minimal_deep_learning_demo.py
More file actions
695 lines (561 loc) · 27.3 KB
/
ultra_minimal_deep_learning_demo.py
File metadata and controls
695 lines (561 loc) · 27.3 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
"""
Ultra Minimal Deep Learning Parkinson's Detection Demo
Only uses Streamlit + NumPy - no other dependencies!
"""
import streamlit as st
import numpy as np
# Page configuration
st.set_page_config(
page_title="Ultra Minimal Deep Learning Parkinson's Detection",
page_icon="🧠",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 3rem;
color: #1f77b4;
text-align: center;
margin-bottom: 2rem;
}
.prediction-box {
background-color: #ffffff;
padding: 1.5rem;
border-radius: 0.5rem;
border-left: 5px solid #1f77b4;
margin: 1rem 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.prediction-box h3 {
color: #2c3e50 !important;
font-size: 1.5rem;
margin-bottom: 1rem;
}
.prediction-box p {
color: #2c3e50 !important;
font-size: 1.1rem;
margin-bottom: 0.5rem;
}
.confidence-high { color: #27ae60 !important; font-weight: bold; }
.confidence-medium { color: #f39c12 !important; font-weight: bold; }
.confidence-low { color: #e74c3c !important; font-weight: bold; }
.neural-network {
background-color: #f8f9fa;
padding: 1rem;
border-radius: 0.5rem;
margin: 1rem 0;
border: 3px solid #1f77b4;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.layer {
background-color: #ffffff;
padding: 1rem;
margin: 0.5rem 0;
border-radius: 0.5rem;
text-align: center;
font-weight: bold;
color: #2c3e50 !important;
font-size: 1.1rem;
border: 2px solid #1f77b4;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.layer:hover {
background-color: #e3f2fd;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}
</style>
""", unsafe_allow_html=True)
class NeuralNetwork:
"""Pure Neural Network implementation using only NumPy"""
def __init__(self, input_size, hidden_sizes, output_size):
self.input_size = input_size
self.hidden_sizes = hidden_sizes
self.output_size = output_size
# Initialize weights and biases
self.weights = []
self.biases = []
# Input to first hidden layer
prev_size = input_size
for hidden_size in hidden_sizes:
self.weights.append(np.random.randn(prev_size, hidden_size) * 0.1)
self.biases.append(np.zeros((1, hidden_size)))
prev_size = hidden_size
# Last hidden to output layer
self.weights.append(np.random.randn(prev_size, output_size) * 0.1)
self.biases.append(np.zeros((1, output_size)))
def sigmoid(self, x):
"""Sigmoid activation function"""
return 1 / (1 + np.exp(-np.clip(x, -500, 500)))
def sigmoid_derivative(self, x):
"""Derivative of sigmoid function"""
s = self.sigmoid(x)
return s * (1 - s)
def forward(self, X):
"""Forward propagation"""
self.activations = [X]
self.z_values = []
current_input = X
for i in range(len(self.weights)):
z = np.dot(current_input, self.weights[i]) + self.biases[i]
self.z_values.append(z)
if i == len(self.weights) - 1: # Output layer
current_input = self.sigmoid(z)
else: # Hidden layers
current_input = self.sigmoid(z)
self.activations.append(current_input)
return current_input
def predict(self, X):
"""Make predictions"""
return self.forward(X)
def train(self, X, y, epochs=1000, learning_rate=0.1):
"""Train the neural network"""
losses = []
for epoch in range(epochs):
# Forward pass
output = self.forward(X)
# Compute loss (mean squared error)
loss = np.mean((output - y) ** 2)
losses.append(loss)
# Backward pass (simplified gradient descent)
error = output - y
# Update weights (simplified version)
for i in reversed(range(len(self.weights))):
if i == len(self.weights) - 1: # Output layer
gradient = error
else:
gradient = np.dot(gradient, self.weights[i + 1].T) * self.sigmoid_derivative(self.z_values[i])
self.weights[i] -= learning_rate * np.dot(self.activations[i].T, gradient) / X.shape[0]
self.biases[i] -= learning_rate * np.mean(gradient, axis=0, keepdims=True)
if epoch % 100 == 0 and epoch > 0:
st.write(f"Epoch {epoch}, Loss: {loss:.4f}")
return losses
class HandwritingAnalyzer:
"""Simple handwriting feature extractor using only NumPy"""
def create_sample_handwriting_matrix(self, is_parkinson=False, size=(10, 10)):
"""Create sample handwriting as a simple matrix"""
matrix = np.ones(size, dtype=float)
center_x, center_y = size[0] // 2, size[1] // 2
if is_parkinson:
# Parkinson's characteristics: more irregular
for i in range(0, 360, 20):
radius = i * 0.1
# Add more randomness for Parkinson's effect
noise_x = np.random.normal(0, 0.5)
noise_y = np.random.normal(0, 0.5)
x = int(center_x + radius * np.cos(np.radians(i)) + noise_x)
y = int(center_y + radius * np.sin(np.radians(i)) + noise_y)
if 0 <= x < size[0] and 0 <= y < size[1]:
matrix[y, x] = 0.0 # Dark pixel
else:
# Healthy characteristics: smooth, regular
for i in range(0, 360, 15):
radius = i * 0.1
x = int(center_x + radius * np.cos(np.radians(i)))
y = int(center_y + radius * np.sin(np.radians(i)))
if 0 <= x < size[0] and 0 <= y < size[1]:
matrix[y, x] = 0.0 # Dark pixel
return matrix
def extract_features(self, matrix):
"""Extract features from handwriting matrix"""
features = []
# Basic statistics
features.extend([
np.mean(matrix),
np.std(matrix),
np.var(matrix),
np.min(matrix),
np.max(matrix)
])
# Edge detection (simple difference)
if matrix.shape[0] > 1 and matrix.shape[1] > 1:
diff_h = np.abs(np.diff(matrix, axis=1))
diff_v = np.abs(np.diff(matrix, axis=0))
features.extend([
np.mean(diff_h),
np.mean(diff_v),
np.sum(diff_h > 0.5), # Edge count
np.sum(diff_v > 0.5)
])
else:
features.extend([0, 0, 0, 0])
return np.array(features)
@st.cache_data
def generate_sample_data():
"""Generate sample voice and handwriting data"""
np.random.seed(42)
# Generate sample voice features (22 features)
n_samples = 100
# Healthy samples (class 0)
healthy_samples = []
for _ in range(50):
features = np.random.normal([120, 140, 90, 0.01, 0.005, 0.005, 0.015, 0.05, 0.02, 0.02, 0.03, 0.04, 0.02, 20, 0.4, 0.8, -5.0, 0.2, 2.0, 0.1, 0.1, 0.1],
[10, 15, 10, 0.005, 0.002, 0.002, 0.005, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 5, 0.1, 0.1, 1.0, 0.1, 0.5, 0.05, 0.05, 0.05])
healthy_samples.append(features)
# Parkinson's samples (class 1)
parkinson_samples = []
for _ in range(50):
features = np.random.normal([100, 120, 80, 0.02, 0.01, 0.01, 0.025, 0.08, 0.04, 0.04, 0.05, 0.06, 0.04, 15, 0.5, 0.9, -6.0, 0.3, 2.5, 0.15, 0.15, 0.15],
[10, 15, 10, 0.005, 0.002, 0.002, 0.005, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 5, 0.1, 0.1, 1.0, 0.1, 0.5, 0.05, 0.05, 0.05])
parkinson_samples.append(features)
# Combine data
X = np.vstack([healthy_samples, parkinson_samples])
y = np.hstack([np.zeros(50), np.ones(50)]).reshape(-1, 1)
return X, y
def display_matrix_as_text(matrix, title):
"""Display matrix as text representation"""
st.markdown(f"**{title}**")
st.text("Matrix representation:")
# Convert to string representation
matrix_str = ""
for row in matrix:
row_str = ""
for val in row:
if val < 0.5:
row_str += "█" # Dark pixel
else:
row_str += "░" # Light pixel
matrix_str += row_str + "\n"
st.text(matrix_str)
def main():
"""Main Streamlit application"""
# Header
st.markdown('<h1 class="main-header">🧠 Ultra Minimal Deep Learning Parkinson\'s Detection</h1>', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; font-size: 1.2rem; color: #7f8c8d;">Pure Neural Networks using ONLY Streamlit + NumPy</p>', unsafe_allow_html=True)
# Sidebar
st.sidebar.title("🔧 Deep Learning Models")
analysis_type = st.sidebar.selectbox(
"Choose Analysis Type",
["Voice Neural Network", "Handwriting Analysis", "Multimodal Fusion", "Complete System Training"]
)
if analysis_type == "Voice Neural Network":
st.markdown("## 🎤 Voice Analysis with Neural Network")
# Load sample data
with st.spinner("Generating voice data..."):
X, y = generate_sample_data()
st.success(f"✅ Generated {len(X)} voice samples")
# Network architecture
st.markdown("### 🧠 Neural Network Architecture")
col1, col2, col3 = st.columns(3)
with col1:
hidden1 = st.slider("Hidden Layer 1", 10, 100, 50)
with col2:
hidden2 = st.slider("Hidden Layer 2", 5, 50, 20)
with col3:
epochs = st.slider("Training Epochs", 100, 1000, 300)
# Display network architecture
st.markdown("### 🏗️ Network Visualization")
architecture_html = f"""
<div class="neural-network">
<h4 style="text-align: center; color: #1f77b4; margin-bottom: 1rem;">🧠 Neural Network Architecture</h4>
<div class="layer">📥 Input Layer: 22 voice features</div>
<div style="text-align: center; color: #666; margin: 0.5rem 0;">⬇️</div>
<div class="layer">🔗 Hidden Layer 1: {hidden1} neurons (sigmoid activation)</div>
<div style="text-align: center; color: #666; margin: 0.5rem 0;">⬇️</div>
<div class="layer">🔗 Hidden Layer 2: {hidden2} neurons (sigmoid activation)</div>
<div style="text-align: center; color: #666; margin: 0.5rem 0;">⬇️</div>
<div class="layer">📤 Output Layer: 1 neuron (sigmoid activation)</div>
<div style="text-align: center; color: #666; margin: 0.5rem 0;">⬇️</div>
<div style="text-align: center; color: #e74c3c; font-weight: bold; padding: 0.5rem; background-color: #ffeaea; border-radius: 0.25rem; margin-top: 0.5rem;">
🎯 Parkinson's Probability (0-1)
</div>
</div>
"""
st.markdown(architecture_html, unsafe_allow_html=True)
if st.button("🚀 Train Neural Network", type="primary"):
with st.spinner("Training neural network..."):
# Create network
nn = NeuralNetwork(
input_size=22,
hidden_sizes=[hidden1, hidden2],
output_size=1
)
# Train network
losses = nn.train(X, y, epochs=epochs, learning_rate=0.01)
st.success("✅ Neural Network trained successfully!")
# Display training loss as text
st.markdown("### 📊 Training Loss Analysis")
col1, col2, col3 = st.columns(3)
final_loss = losses[-1]
with col1:
st.metric("🎯 Final Loss", f"{final_loss:.4f}")
with col2:
st.metric("🚀 Initial Loss", f"{losses[0]:.4f}")
with col3:
reduction = ((losses[0] - final_loss) / losses[0] * 100)
st.metric("📈 Loss Reduction", f"{reduction:.1f}%")
# Create a simple text-based loss visualization
st.markdown("**📉 Training Loss Progression:**")
loss_text = "```\n"
loss_text += f"Epoch Loss\n"
loss_text += f"----- ----\n"
# Show key epochs
key_epochs = [0, len(losses)//4, len(losses)//2, 3*len(losses)//4, len(losses)-1]
for epoch in key_epochs:
if epoch < len(losses):
loss_text += f"{epoch:5d} {losses[epoch]:.4f}\n"
loss_text += "```"
st.markdown(loss_text)
# Show last 10 losses in a more readable format
st.markdown("**📋 Last 10 Training Epochs:**")
for i, loss in enumerate(losses[-10:]):
epoch_num = len(losses)-10+i
st.markdown(f"• **Epoch {epoch_num}:** Loss = {loss:.4f}")
# Test on sample
test_sample = X[0:1]
prediction = nn.predict(test_sample)[0, 0]
st.markdown("### 📊 Prediction Results")
risk_level = prediction
if risk_level > 0.7:
risk_color = "🔴"
risk_text = "High Risk"
confidence_class = "confidence-high"
elif risk_level > 0.4:
risk_color = "🟡"
risk_text = "Moderate Risk"
confidence_class = "confidence-medium"
else:
risk_color = "🟢"
risk_text = "Low Risk"
confidence_class = "confidence-low"
st.markdown(f"""
<div class="prediction-box">
<h3>{risk_color} Neural Network Prediction: {risk_text}</h3>
<p><strong>Parkinson's Probability:</strong> {risk_level:.1%}</p>
<p><strong>Healthy Probability:</strong> {1-risk_level:.1%}</p>
<p><strong>Model Confidence:</strong> <span class="{confidence_class}">{max(risk_level, 1-risk_level):.1%}</span></p>
</div>
""", unsafe_allow_html=True)
elif analysis_type == "Handwriting Analysis":
st.markdown("## ✍️ Handwriting Analysis with Neural Networks")
# Create handwriting analyzer
analyzer = HandwritingAnalyzer()
st.markdown("### 🖼️ Sample Handwriting Matrices")
col1, col2 = st.columns(2)
with col1:
st.markdown("**Healthy Sample**")
healthy_matrix = analyzer.create_sample_handwriting_matrix(is_parkinson=False)
display_matrix_as_text(healthy_matrix, "Healthy Handwriting")
# Extract features
healthy_features = analyzer.extract_features(healthy_matrix)
st.markdown("**Extracted Features:**")
st.write(f"- Mean intensity: {healthy_features[0]:.3f}")
st.write(f"- Standard deviation: {healthy_features[1]:.3f}")
st.write(f"- Edge count: {healthy_features[8]:.0f}")
with col2:
st.markdown("**Parkinson's Sample**")
parkinson_matrix = analyzer.create_sample_handwriting_matrix(is_parkinson=True)
display_matrix_as_text(parkinson_matrix, "Parkinson's Handwriting")
# Extract features
parkinson_features = analyzer.extract_features(parkinson_matrix)
st.markdown("**Extracted Features:**")
st.write(f"- Mean intensity: {parkinson_features[0]:.3f}")
st.write(f"- Standard deviation: {parkinson_features[1]:.3f}")
st.write(f"- Edge count: {parkinson_features[8]:.0f}")
# Feature comparison
st.markdown("### 📊 Feature Comparison")
comparison_data = {
'Feature': ['Mean Intensity', 'Std Deviation', 'Variance', 'Edge Count'],
'Healthy': [healthy_features[0], healthy_features[1], healthy_features[2], healthy_features[8]],
'Parkinson\'s': [parkinson_features[0], parkinson_features[1], parkinson_features[2], parkinson_features[8]]
}
# Display as table
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Feature**")
for feature in comparison_data['Feature']:
st.write(feature)
with col2:
st.markdown("**Healthy**")
for value in comparison_data['Healthy']:
st.write(f"{value:.3f}")
with col3:
st.markdown("**Parkinson's**")
for value in comparison_data['Parkinson\'s']:
st.write(f"{value:.3f}")
# Simple classification
st.markdown("### 🤖 Handwriting Classification")
if st.button("🔍 Classify Handwriting", type="primary"):
# Create training data
healthy_samples = []
parkinson_samples = []
for _ in range(20):
healthy_samples.append(analyzer.extract_features(analyzer.create_sample_handwriting_matrix(False)))
parkinson_samples.append(analyzer.extract_features(analyzer.create_sample_handwriting_matrix(True)))
X_hand = np.vstack([healthy_samples, parkinson_samples])
y_hand = np.hstack([np.zeros(20), np.ones(20)]).reshape(-1, 1)
# Train simple neural network for handwriting
hand_nn = NeuralNetwork(
input_size=len(healthy_features),
hidden_sizes=[10, 5],
output_size=1
)
with st.spinner("Training handwriting classifier..."):
hand_nn.train(X_hand, y_hand, epochs=200, learning_rate=0.1)
# Test on current samples
healthy_pred = hand_nn.predict(healthy_features.reshape(1, -1))[0, 0]
parkinson_pred = hand_nn.predict(parkinson_features.reshape(1, -1))[0, 0]
col1, col2 = st.columns(2)
with col1:
st.metric("Healthy Sample Prediction", f"{healthy_pred:.1%}", "Parkinson's risk")
with col2:
st.metric("Parkinson's Sample Prediction", f"{parkinson_pred:.1%}", "Parkinson's risk")
elif analysis_type == "Multimodal Fusion":
st.markdown("## 🔄 Multimodal Fusion Analysis")
st.markdown("### 🎯 Combining Voice + Handwriting Predictions")
# Simulate multimodal predictions
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**🎤 Voice Model**")
voice_prob = st.slider("Voice Parkinson's Probability", 0.0, 1.0, 0.3)
st.metric("Voice Risk", f"{voice_prob:.1%}")
with col2:
st.markdown("**✍️ Handwriting Model**")
hand_prob = st.slider("Handwriting Parkinson's Probability", 0.0, 1.0, 0.4)
st.metric("Handwriting Risk", f"{hand_prob:.1%}")
with col3:
st.markdown("**🔄 Fusion Model**")
# Simple fusion: weighted average
fusion_prob = 0.6 * voice_prob + 0.4 * hand_prob
st.metric("Fused Risk", f"{fusion_prob:.1%}")
# Fusion visualization using text
st.markdown("### 📊 Fusion Visualization")
# Create a simple text-based visualization
fusion_text = f"""
```
Voice Model: {'█' * int(voice_prob * 20):20} {voice_prob:.1%}
Handwriting Model: {'█' * int(hand_prob * 20):20} {hand_prob:.1%}
Fusion Model: {'█' * int(fusion_prob * 20):20} {fusion_prob:.1%}
Threshold: {'█' * 10:20} 50%
```
"""
st.text(fusion_text)
# Final assessment
st.markdown("### 🎯 Final Assessment")
if fusion_prob > 0.7:
risk_color = "🔴"
risk_text = "High Risk"
recommendation = "Immediate clinical evaluation recommended"
elif fusion_prob > 0.4:
risk_color = "🟡"
risk_text = "Moderate Risk"
recommendation = "Clinical follow-up recommended"
else:
risk_color = "🟢"
risk_text = "Low Risk"
recommendation = "Continue regular monitoring"
st.markdown(f"""
<div class="prediction-box">
<h3>{risk_color} Final Assessment: {risk_text}</h3>
<p><strong>Fused Probability:</strong> {fusion_prob:.1%}</p>
<p><strong>Recommendation:</strong> {recommendation}</p>
<p><strong>Confidence:</strong> Based on multimodal analysis</p>
</div>
""", unsafe_allow_html=True)
elif analysis_type == "Complete System Training":
st.markdown("## 🎓 Complete Multimodal System Training")
st.markdown("### 🏗️ Training Both Models Simultaneously")
# Network architectures
col1, col2 = st.columns(2)
with col1:
st.markdown("**Voice Network**")
voice_layers = st.multiselect(
"Select hidden layers for voice model:",
[10, 20, 30, 50, 100],
default=[50, 20]
)
with col2:
st.markdown("**Handwriting Network**")
hand_layers = st.multiselect(
"Select hidden layers for handwriting model:",
[5, 10, 15, 20],
default=[10, 5]
)
if st.button("🚀 Train Complete Multimodal System", type="primary"):
with st.spinner("Training complete multimodal system..."):
# Load voice data
X_voice, y_voice = generate_sample_data()
# Train voice network
st.write("Training voice neural network...")
voice_nn = NeuralNetwork(
input_size=22,
hidden_sizes=voice_layers,
output_size=1
)
voice_losses = voice_nn.train(X_voice, y_voice, epochs=200, learning_rate=0.01)
# Train handwriting network
st.write("Training handwriting neural network...")
analyzer = HandwritingAnalyzer()
# Create handwriting training data
hand_features = []
hand_labels = []
for _ in range(50):
# Healthy samples
healthy_matrix = analyzer.create_sample_handwriting_matrix(False)
healthy_feat = analyzer.extract_features(healthy_matrix)
hand_features.append(healthy_feat)
hand_labels.append(0)
# Parkinson's samples
parkinson_matrix = analyzer.create_sample_handwriting_matrix(True)
parkinson_feat = analyzer.extract_features(parkinson_matrix)
hand_features.append(parkinson_feat)
hand_labels.append(1)
X_hand = np.array(hand_features)
y_hand = np.array(hand_labels).reshape(-1, 1)
hand_nn = NeuralNetwork(
input_size=len(hand_features[0]),
hidden_sizes=hand_layers,
output_size=1
)
hand_losses = hand_nn.train(X_hand, y_hand, epochs=200, learning_rate=0.01)
st.success("✅ Complete multimodal system trained!")
# Display training results
col1, col2 = st.columns(2)
with col1:
st.markdown("**Voice Model Training:**")
st.metric("Final Loss", f"{voice_losses[-1]:.4f}")
st.metric("Initial Loss", f"{voice_losses[0]:.4f}")
with col2:
st.markdown("**Handwriting Model Training:**")
st.metric("Final Loss", f"{hand_losses[-1]:.4f}")
st.metric("Initial Loss", f"{hand_losses[0]:.4f}")
# Test the system
st.markdown("### 🧪 System Testing")
# Test on sample
test_voice = X_voice[0:1]
test_hand_matrix = analyzer.create_sample_handwriting_matrix(False)
test_hand_feat = analyzer.extract_features(test_hand_matrix).reshape(1, -1)
voice_pred = voice_nn.predict(test_voice)[0, 0]
hand_pred = hand_nn.predict(test_hand_feat)[0, 0]
# Fusion
fusion_pred = 0.6 * voice_pred + 0.4 * hand_pred
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Voice Model", f"{voice_pred:.1%}")
with col2:
st.metric("Handwriting Model", f"{hand_pred:.1%}")
with col3:
st.metric("Fusion Model", f"{fusion_pred:.1%}")
st.markdown("### 🏆 Model Performance Summary")
st.markdown(f"""
- **Voice Network**: {len(voice_layers)} hidden layers, {22} → {voice_layers} → {1} neurons
- **Handwriting Network**: {len(hand_layers)} hidden layers, {len(hand_features[0])} → {hand_layers} → {1} neurons
- **Fusion Strategy**: Weighted average (60% voice, 40% handwriting)
- **Total Parameters**: ~{sum(voice_layers) + len(voice_layers)*22 + sum(hand_layers) + len(hand_layers)*len(hand_features[0])} weights
""")
# Footer
st.markdown("---")
st.markdown("### 📝 Ultra Minimal Deep Learning Features")
st.info("""
**This demo showcases:**
- 🧠 **Pure Neural Networks**: Custom implementation using ONLY NumPy
- 🎤 **Voice Analysis**: 22-feature neural network with configurable architecture
- ✍️ **Handwriting Analysis**: Matrix-based feature extraction and classification
- 🔄 **Multimodal Fusion**: Combining predictions from multiple models
- 🎓 **Interactive Training**: Real-time model training and architecture selection
- 📊 **Text-based Visualization**: No external plotting libraries needed
**Zero Dependencies**: Only Streamlit + NumPy - works with any Python environment!
""")
if __name__ == "__main__":
main()