Repository navigation
Expand file tree
/
Copy pathguided_tutorials.py
More file actions
2639 lines (2078 loc) · 101 KB
/
Copy pathguided_tutorials.py
File metadata and controls
2639 lines (2078 loc) · 101 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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import tensorflow as tf
from PIL import Image
import plotly.graph_objects as go
import io
import time
import cv2
import pandas as pd
from scipy.signal import convolve2d
# Set random seeds for reproducibility
np.random.seed(42)
torch.manual_seed(42)
tf.random.set_seed(42)
# Function to create a simple sample image for convolution demonstration
def create_sample_image(type="edge", size=32):
"""Create a sample image for convolution demonstration"""
img = np.zeros((size, size))
if type == "edge":
# Create a simple edge
img[size//4:3*size//4, size//2:] = 1.0
elif type == "corner":
# Create a simple corner
img[size//4:3*size//4, size//4:3*size//4] = 1.0
elif type == "gradient":
# Create a gradient
for i in range(size):
img[i, :] = i / size
elif type == "circle":
# Create a circle
center = size // 2
radius = size // 4
for i in range(size):
for j in range(size):
if (i - center) ** 2 + (j - center) ** 2 < radius ** 2:
img[i, j] = 1.0
elif type == "cross":
# Create a cross
img[size//4:3*size//4, size//2-1:size//2+2] = 1.0
img[size//2-1:size//2+2, size//4:3*size//4] = 1.0
return img
# Common CNN filters
COMMON_FILTERS = {
"Horizontal Edge Detection": np.array([
[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]
]),
"Vertical Edge Detection": np.array([
[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]
]),
"Sobel Horizontal": np.array([
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]
]),
"Sobel Vertical": np.array([
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
]),
"Gaussian Blur": np.array([
[1/16, 1/8, 1/16],
[1/8, 1/4, 1/8],
[1/16, 1/8, 1/16]
]),
"Sharpen": np.array([
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]
]),
"Identity": np.array([
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]),
"Ridge Detection": np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
])
}
def apply_convolution(image, kernel):
"""Apply convolution with the given kernel"""
# Ensure the image is a 2D array
if len(image.shape) > 2:
image = np.mean(image, axis=2) # Convert to grayscale
# Apply convolution
result = convolve2d(image, kernel, mode='same', boundary='symm')
# Normalize to [0, 1] range for better visualization
result = (result - result.min()) / (result.max() - result.min() + 1e-8)
return result
def apply_pooling(image, pool_type="max", pool_size=2, stride=2):
"""Apply pooling operation"""
# Get image dimensions
h, w = image.shape
# Output dimensions
h_out = (h - pool_size) // stride + 1
w_out = (w - pool_size) // stride + 1
# Initialize output
result = np.zeros((h_out, w_out))
# Apply pooling
for i in range(h_out):
for j in range(w_out):
# Extract region
i_start = i * stride
j_start = j * stride
region = image[i_start:i_start+pool_size, j_start:j_start+pool_size]
if pool_type == "max":
result[i, j] = np.max(region)
elif pool_type == "avg":
result[i, j] = np.mean(region)
return result
def apply_activation(feature_map, activation_type="relu"):
"""Apply activation function"""
if activation_type == "relu":
return np.maximum(0, feature_map)
elif activation_type == "sigmoid":
return 1 / (1 + np.exp(-feature_map))
elif activation_type == "tanh":
return np.tanh(feature_map)
else:
return feature_map
def guided_tutorials():
st.title("Guided CNN Tutorials")
st.markdown("""
# Interactive CNN Tutorials
Explore these interactive tutorials to understand how Convolutional Neural Networks work.
Each tutorial focuses on a specific aspect of CNNs with interactive visualizations and step-by-step explanations.
## Tutorial Topics:
- Convolution Operation: Learn how filters detect features in images
- Activation Functions: Understand the role of non-linearity in neural networks
- Pooling Operations: See how spatial dimensions are reduced while preserving features
- CNN Architecture Flow: Follow data through a complete CNN pipeline
""")
# Tutorial selection
tutorial = st.selectbox(
"Select a Tutorial:",
["Convolution Operation", "Activation Functions", "Pooling Operations", "CNN Architecture Flow", "CNN Training Concepts", "Quiz: Test Your Knowledge"]
)
if tutorial == "Convolution Operation":
convolution_tutorial()
elif tutorial == "Activation Functions":
activation_tutorial()
elif tutorial == "Pooling Operations":
pooling_tutorial()
elif tutorial == "CNN Architecture Flow":
architecture_flow_tutorial()
elif tutorial == "CNN Training Concepts":
training_concepts_tutorial()
elif tutorial == "Quiz: Test Your Knowledge":
cnn_quiz()
def convolution_tutorial():
st.subheader("Understanding Convolution")
st.markdown("""
## The Convolution Operation
Convolution is the fundamental operation in CNN that helps detect features like edges, textures, and patterns in images.
### How it Works:
1. A small **filter** (or kernel) slides across the input image
2. At each position, element-wise multiplication and summation is performed
3. The result is stored in a new output image called a **feature map**
Different filters detect different features. Let's explore some common filters:
""")
# Interactive convolution demonstration
col1, col2 = st.columns(2)
with col1:
# Sample image selection
image_type = st.selectbox(
"Select Sample Image:",
["edge", "corner", "gradient", "circle", "cross"]
)
# Create the sample image
sample_img = create_sample_image(image_type)
# Display the sample image
st.image(sample_img, caption="Sample Image", use_container_width=True, clamp=True)
with col2:
# Filter selection
filter_name = st.selectbox(
"Select Filter:",
list(COMMON_FILTERS.keys())
)
# Get the selected filter
selected_filter = COMMON_FILTERS[filter_name]
# Display the filter
st.markdown(f"**{filter_name} Filter:**")
fig, ax = plt.subplots(figsize=(4, 4))
im = ax.imshow(selected_filter, cmap='viridis')
plt.colorbar(im, ax=ax)
# Add filter values as text
for i in range(selected_filter.shape[0]):
for j in range(selected_filter.shape[1]):
text = ax.text(j, i, f"{selected_filter[i, j]:.2f}",
ha="center", va="center", color="w" if abs(selected_filter[i, j]) > 0.5 else "k")
ax.set_title(f"{filter_name}")
st.pyplot(fig)
# Apply convolution and show result
st.subheader("Convolution Result")
# Apply the convolution
conv_result = apply_convolution(sample_img, selected_filter)
# Display the result
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
st.markdown("**Input Image**")
st.image(sample_img, caption="Input", use_container_width=True, clamp=True)
with col2:
st.markdown("**Filter**")
filter_img = (selected_filter - selected_filter.min()) / (selected_filter.max() - selected_filter.min())
st.image(filter_img, caption=filter_name, use_container_width=True, clamp=True)
with col3:
st.markdown("**Feature Map**")
st.image(conv_result, caption="Output", use_container_width=True, clamp=True)
# Visualize convolution in 3D
st.subheader("3D Visualization of Convolution")
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(121, projection='3d')
# Create meshgrid for 3D plot
x = np.arange(0, sample_img.shape[1])
y = np.arange(0, sample_img.shape[0])
X, Y = np.meshgrid(x, y)
# Plot the input image in 3D
surf = ax.plot_surface(X, Y, sample_img, cmap='viridis', alpha=0.8)
ax.set_title("Input Image")
# Plot the convolution result in 3D
ax = fig.add_subplot(122, projection='3d')
surf = ax.plot_surface(X, Y, conv_result, cmap='plasma', alpha=0.8)
ax.set_title("Convolution Result")
plt.tight_layout()
st.pyplot(fig)
# Interactive explanation of filter purpose
st.subheader("Understanding This Filter")
filter_explanations = {
"Horizontal Edge Detection": """
This filter detects **horizontal edges** by taking the difference between the pixel values above and below.
- Positive values in bottom row: Highlights transitions from dark to light (top to bottom)
- Negative values in top row: Highlights transitions from light to dark (top to bottom)
- Zero values in middle row: Ignores horizontal lines
**Applications**: Finding horizontal lines in images, text line detection
""",
"Vertical Edge Detection": """
This filter detects **vertical edges** by taking the difference between pixel values on the left and right.
- Positive values in right column: Highlights transitions from dark to light (left to right)
- Negative values in left column: Highlights transitions from light to dark (left to right)
- Zero values in middle column: Ignores vertical lines
**Applications**: Finding vertical boundaries, detecting columns or buildings
""",
"Sobel Horizontal": """
The **Sobel horizontal filter** is an improved edge detector that adds emphasis to central pixels.
- Stronger weights in the middle columns (×2): Gives more importance to central pixels
- Similar to Horizontal Edge Detection but with better noise handling
**Applications**: Image processing pipelines, detecting more defined horizontal edges
""",
"Sobel Vertical": """
The **Sobel vertical filter** is an improved edge detector for vertical edges with emphasis on central pixels.
- Stronger weights in the middle rows (×2): Gives more importance to central pixels
- Similar to Vertical Edge Detection but with better noise handling
**Applications**: Image processing pipelines, detecting more defined vertical edges
""",
"Gaussian Blur": """
The **Gaussian blur filter** averages pixels with their neighbors, giving more weight to closer pixels.
- Highest weight in center (1/4): Most influence from the center pixel
- Decreasing weights with distance: Less influence from farther pixels
- All positive values: Performs weighted averaging
**Applications**: Noise reduction, pre-processing for feature detection, creating smooth effects
""",
"Sharpen": """
The **Sharpen filter** enhances details by increasing the weight of the center pixel relative to its neighbors.
- High positive value in center (5): Emphasizes the center pixel
- Negative values around: Subtracts neighboring pixels
- Net effect: Amplifies differences between a pixel and its surroundings
**Applications**: Detail enhancement, making blurry images clearer, emphasizing textures
""",
"Identity": """
The **Identity filter** simply passes through the original image values.
- 1 in center, 0 elsewhere: Only keeps the center pixel value
- Result is identical to input (hence the name)
**Applications**: Used as a baseline or for certain skip connections in deep networks
""",
"Ridge Detection": """
The **Ridge Detection filter** (also called Laplacian) detects areas where intensity changes direction.
- High positive weight in center (8): Emphasizes the center
- Negative values around (-1): Subtracts all neighbors
- Net effect: Highlights regions where the image changes concavity
**Applications**: Finding ridges, detecting complete boundaries, highlighting areas where the gradient changes direction
"""
}
if filter_name in filter_explanations:
st.markdown(filter_explanations[filter_name])
# Practical exercise
st.subheader("Hands-on Exercise")
st.markdown("""
### Custom Filter Creation
Now it's your turn! Create a custom filter and see how it affects the image.
Experiment with different values to understand how each position in the filter influences the result.
""")
# Create a grid of input fields for a 3x3 filter
custom_filter = np.zeros((3, 3))
cols = st.columns(3)
for i in range(3):
for j in range(3):
with cols[j]:
custom_filter[i, j] = st.number_input(
f"Filter[{i},{j}]",
min_value=-10.0,
max_value=10.0,
value=0.0,
step=0.1,
key=f"custom_filter_{i}_{j}"
)
# Normalize the filter (optional)
normalize_filter = st.checkbox("Normalize Filter (sum to 1)", value=False)
if normalize_filter and np.sum(np.abs(custom_filter)) > 0:
custom_filter = custom_filter / np.sum(np.abs(custom_filter))
# Apply the custom filter
custom_result = apply_convolution(sample_img, custom_filter)
# Display the result
col1, col2 = st.columns(2)
with col1:
st.markdown("**Custom Filter**")
fig, ax = plt.subplots(figsize=(4, 4))
im = ax.imshow(custom_filter, cmap='viridis')
plt.colorbar(im, ax=ax)
# Add filter values as text
for i in range(custom_filter.shape[0]):
for j in range(custom_filter.shape[1]):
text = ax.text(j, i, f"{custom_filter[i, j]:.2f}",
ha="center", va="center", color="w" if abs(custom_filter[i, j]) > 0.5 else "k")
ax.set_title("Custom Filter")
st.pyplot(fig)
with col2:
st.markdown("**Result with Custom Filter**")
st.image(custom_result, caption="Custom Filter Result", use_container_width=True, clamp=True)
# Learning checkpoints
st.subheader("Key Takeaways")
st.markdown("""
### What You've Learned:
- **Convolution** involves sliding a filter over an image and computing the sum of element-wise multiplications
- Different **filters** detect different features (edges, textures, patterns)
- The resulting **feature maps** highlight specific attributes of the image
- In CNNs, these filters are **learned automatically** during training
- Multiple filters create multiple feature maps, allowing the network to detect various features
### Next Steps:
After convolution, CNNs typically apply an activation function, which introduces non-linearity.
Proceed to the Activation Functions tutorial to learn more.
""")
# Navigation buttons
col1, col2 = st.columns(2)
with col1:
st.markdown("⬅️ [Return to Tutorial Selection](#guided-cnn-tutorials)")
with col2:
st.markdown("➡️ [Next: Activation Functions](#)")
def activation_tutorial():
st.subheader("Understanding Activation Functions")
st.markdown("""
## Activation Functions in CNNs
Activation functions introduce **non-linearity** into neural networks, which is crucial for learning complex patterns.
Without them, a neural network would just be a series of linear transformations.
### Why Non-Linearity Matters:
- Enables the network to learn **complex, non-linear relationships** in data
- Allows **hierarchical feature learning** across multiple layers
- Makes the network capable of approximating any function (universal approximation theorem)
Let's explore common activation functions and see how they transform feature maps:
""")
# Interactive activation function demonstration
col1, col2 = st.columns(2)
with col1:
# Input selection
input_type = st.selectbox(
"Select Input (After Convolution):",
["edge", "corner", "gradient", "circle", "cross"]
)
# Select filter to apply
filter_name = st.selectbox(
"Apply Filter:",
list(COMMON_FILTERS.keys())
)
# Create the sample image
sample_img = create_sample_image(input_type)
# Apply convolution
selected_filter = COMMON_FILTERS[filter_name]
conv_result = apply_convolution(sample_img, selected_filter)
# Display the input and convolution result
st.markdown("**Original Image:**")
st.image(sample_img, caption="Input Image", use_container_width=True, clamp=True)
st.markdown("**After Convolution:**")
st.image(conv_result, caption=f"Convolved with {filter_name}", use_container_width=True, clamp=True)
with col2:
# Activation function selection
activation_type = st.selectbox(
"Select Activation Function:",
["ReLU", "Sigmoid", "Tanh", "Leaky ReLU", "None (Linear)"]
)
# Apply activation function
if activation_type == "ReLU":
result = apply_activation(conv_result, "relu")
formula = "ReLU(x) = max(0, x)"
description = """
**ReLU (Rectified Linear Unit)**:
- Outputs the input directly if positive, otherwise outputs zero
- Simple, computationally efficient
- Helps with the vanishing gradient problem
- Most commonly used in modern CNNs
- Can suffer from "dying ReLU" problem (neurons permanently inactive)
"""
elif activation_type == "Sigmoid":
result = apply_activation(conv_result, "sigmoid")
formula = "Sigmoid(x) = 1 / (1 + e^(-x))"
description = """
**Sigmoid**:
- Squashes values between 0 and 1
- Smooth, differentiable function
- Historically popular, now less common in hidden layers
- Can cause vanishing gradient problem in deep networks
- Often used for binary classification output layer
"""
elif activation_type == "Tanh":
result = apply_activation(conv_result, "tanh")
formula = "Tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))"
description = """
**Tanh (Hyperbolic Tangent)**:
- Squashes values between -1 and 1
- Zero-centered, which helps with optimization
- Generally performs better than sigmoid for hidden layers
- Still can suffer from vanishing gradient problem
- Good for data with both positive and negative values
"""
elif activation_type == "Leaky ReLU":
# Custom implementation for Leaky ReLU
alpha = st.slider("Alpha value (slope for negative inputs):", 0.01, 0.5, 0.1)
result = np.maximum(alpha * conv_result, conv_result)
formula = f"LeakyReLU(x) = max(αx, x), where α = {alpha}"
description = f"""
**Leaky ReLU**:
- Similar to ReLU, but allows a small gradient for negative values (α = {alpha})
- Addresses the "dying ReLU" problem
- Maintains the computational efficiency of ReLU
- Better gradient flow during backpropagation
- Used in many modern architectures as an alternative to ReLU
"""
else: # No activation
result = conv_result
formula = "f(x) = x"
description = """
**Linear (No Activation)**:
- Simply passes the input value unchanged
- Provides no non-linearity
- Multiple stacked linear layers would be equivalent to a single linear layer
- Rarely used in hidden layers, sometimes in network output for regression
"""
# Display the formula
st.markdown(f"**Formula:** {formula}")
# Display the result after activation
st.markdown("**After Activation:**")
st.image(result, caption=f"After {activation_type}", use_container_width=True, clamp=True)
# Display description
st.markdown(description)
# 3D visualization of activation effect
st.subheader("3D Visualization of Activation Effect")
# Setup for the 3D visualization
x = np.arange(0, conv_result.shape[1])
y = np.arange(0, conv_result.shape[0])
x_mesh, y_mesh = np.meshgrid(x, y)
# Create the 3D visualization with Plotly
fig = go.Figure()
# Add the surface for convolution result (before activation)
fig.add_trace(go.Surface(
z=conv_result,
x=x_mesh,
y=y_mesh,
colorscale='Viridis',
opacity=0.7,
showscale=False,
name="Before Activation"
))
# Add the surface for activation result
fig.add_trace(go.Surface(
z=result,
x=x_mesh,
y=y_mesh,
colorscale='Plasma',
opacity=0.9,
showscale=True,
colorbar=dict(title="After Activation"),
name="After Activation"
))
fig.update_layout(
title=f"Effect of {activation_type} Activation",
scene=dict(
xaxis_title='X',
yaxis_title='Y',
zaxis_title='Activation Value',
camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
),
width=800,
height=600,
margin=dict(l=0, r=0, b=0, t=40)
)
st.plotly_chart(fig)
# Interactive 1D visualization of activation functions
st.subheader("Interactive Visualization of Activation Functions")
st.markdown("""
This graph shows how each activation function transforms input values.
Move the slider to see how different input ranges are affected.
""")
# Range for input values
x_min = st.slider("Minimum Input Value:", -10.0, 0.0, -5.0)
x_max = st.slider("Maximum Input Value:", 0.0, 10.0, 5.0)
# Generate input values
x = np.linspace(x_min, x_max, 1000)
# Calculate activation function outputs
relu = np.maximum(0, x)
sigmoid = 1 / (1 + np.exp(-x))
tanh = np.tanh(x)
leaky_relu = np.maximum(0.1 * x, x)
# Create the plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, x, 'k--', label='Linear (No Activation)')
ax.plot(x, relu, label='ReLU')
ax.plot(x, sigmoid, label='Sigmoid')
ax.plot(x, tanh, label='Tanh')
ax.plot(x, leaky_relu, label='Leaky ReLU (α=0.1)')
ax.set_xlabel('Input (x)')
ax.set_ylabel('Output (y)')
ax.set_title('Comparing Activation Functions')
ax.grid(True, alpha=0.3)
ax.legend()
ax.axhline(y=0, color='gray', linestyle='-', alpha=0.3)
ax.axvline(x=0, color='gray', linestyle='-', alpha=0.3)
st.pyplot(fig)
# Practical application of activation functions
st.subheader("Practical Application: Feature Enhancement")
st.markdown("""
Activation functions can significantly impact what features are highlighted in an image.
Here we see how different activations affect feature extraction:
""")
# Create a more complex sample image
complex_img = create_sample_image("circle", size=64)
# Apply a few different filters and activations
filters_to_show = ["Horizontal Edge Detection", "Vertical Edge Detection", "Ridge Detection"]
activations_to_show = ["None (Linear)", "ReLU", "Sigmoid"]
# Create a grid to show the results
fig, axs = plt.subplots(len(filters_to_show), len(activations_to_show) + 1, figsize=(12, 8))
# Add titles to columns
axs[0, 0].set_title("Filter")
for j, act in enumerate(activations_to_show):
axs[0, j+1].set_title(act)
for i, filter_name in enumerate(filters_to_show):
# Get the filter
curr_filter = COMMON_FILTERS[filter_name]
# Apply convolution
conv_result = apply_convolution(complex_img, curr_filter)
# Show the filter
axs[i, 0].imshow(curr_filter, cmap='viridis')
axs[i, 0].set_ylabel(filter_name)
axs[i, 0].set_xticks([])
axs[i, 0].set_yticks([])
# Show results with different activations
for j, act in enumerate(activations_to_show):
if act == "None (Linear)":
result = conv_result
elif act == "ReLU":
result = apply_activation(conv_result, "relu")
elif act == "Sigmoid":
result = apply_activation(conv_result, "sigmoid")
axs[i, j+1].imshow(result, cmap='plasma')
axs[i, j+1].set_xticks([])
axs[i, j+1].set_yticks([])
plt.tight_layout()
st.pyplot(fig)
# Learning checkpoints
st.subheader("Key Takeaways")
st.markdown("""
### What You've Learned:
- **Activation functions** add non-linearity to neural networks
- **ReLU** is most commonly used due to its simplicity and effectiveness
- Different activations have different properties:
- **ReLU & Leaky ReLU**: Good for deep networks, help with vanishing gradients
- **Sigmoid & Tanh**: Squash values to bounded ranges, useful for certain tasks
- Activations determine which features are emphasized or suppressed
- Modern CNNs typically use ReLU or variants like Leaky ReLU
### Next Steps:
After activation, CNNs typically use pooling to reduce spatial dimensions.
Proceed to the Pooling Operations tutorial to learn more.
""")
# Navigation buttons
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("⬅️ [Return to Tutorial Selection](#guided-cnn-tutorials)")
with col2:
st.markdown("⬅️ [Previous: Convolution Operation](#)")
with col3:
st.markdown("➡️ [Next: Pooling Operations](#)")
def pooling_tutorial():
st.subheader("Understanding Pooling Operations")
st.markdown("""
## Pooling in CNNs
Pooling operations reduce the spatial dimensions (width and height) of feature maps while preserving important information.
### Key Benefits of Pooling:
1. **Dimensionality Reduction** - Reduces computation by decreasing feature map size
2. **Translation Invariance** - Makes detection less sensitive to exact feature location
3. **Feature Abstraction** - Helps capture hierarchical patterns at different scales
4. **Overfitting Prevention** - Reduces model parameters and adds robustness
Let's explore different pooling operations:
""")
# Interactive pooling demonstration
col1, col2 = st.columns(2)
with col1:
# Input selection and processing
input_type = st.selectbox(
"Select Input Image:",
["circle", "edge", "corner", "gradient", "cross"]
)
# Create the sample image (making it larger to better show pooling)
sample_img = create_sample_image(input_type, size=64)
# Apply some convolution to create a more interesting feature map
filter_name = st.selectbox(
"Apply Filter Before Pooling:",
list(COMMON_FILTERS.keys())
)
# Apply convolution and activation
selected_filter = COMMON_FILTERS[filter_name]
conv_result = apply_convolution(sample_img, selected_filter)
# Apply activation function
activation_type = st.selectbox(
"Apply Activation Before Pooling:",
["None (Linear)", "ReLU", "Sigmoid", "Tanh"]
)
if activation_type == "ReLU":
feature_map = apply_activation(conv_result, "relu")
elif activation_type == "Sigmoid":
feature_map = apply_activation(conv_result, "sigmoid")
elif activation_type == "Tanh":
feature_map = apply_activation(conv_result, "tanh")
else:
feature_map = conv_result
# Display the input and processed feature map
st.markdown("**Original Image:**")
st.image(sample_img, caption="Input Image", use_container_width=True, clamp=True)
st.markdown("**Feature Map (After Convolution & Activation):**")
st.image(feature_map, caption="Feature Map", use_container_width=True, clamp=True)
with col2:
# Pooling options
pooling_type = st.selectbox(
"Select Pooling Type:",
["Max Pooling", "Average Pooling"]
)
# Pooling parameters
pool_size = st.slider("Pool Size:", 2, 8, 2)
stride = st.slider("Stride:", 1, pool_size, pool_size)
# Apply pooling
if pooling_type == "Max Pooling":
pooled_result = apply_pooling(feature_map, "max", pool_size, stride)
description = f"""
**Max Pooling (pool_size={pool_size}, stride={stride})**:
- Takes the **maximum value** from each region
- Emphasizes the strongest features or activations
- Preserves sharp features and high activations
- Most commonly used in modern CNNs
- Effective for detecting the presence of specific features
"""
else: # Average Pooling
pooled_result = apply_pooling(feature_map, "avg", pool_size, stride)
description = f"""
**Average Pooling (pool_size={pool_size}, stride={stride})**:
- Takes the **average value** from each region
- Smooths out activations in each pooling window
- Better preserves background/context information
- Less common but useful for certain tasks
- Can help reduce noise in feature maps
"""
# Show pooling visualization
st.markdown("**After Pooling:**")
st.image(pooled_result, caption=f"After {pooling_type}", use_container_width=True, clamp=True)
# Show pooling description
st.markdown(description)
# Show output dimensions
st.markdown(f"""
**Input Shape**: {feature_map.shape[0]} × {feature_map.shape[1]}
**Output Shape**: {pooled_result.shape[0]} × {pooled_result.shape[1]}
**Reduction**: {feature_map.size} → {pooled_result.size} pixels ({100 * pooled_result.size / feature_map.size:.1f}% of original)
""")
# Visual explanation of pooling
st.subheader("Visual Explanation of Pooling")
st.markdown("""
This visualization shows how pooling works on a small section of the feature map.
The colored grid represents a region of the feature map, and the pooling operation computes a single output value from each window.
""")
# Create a visual explanation of pooling
# First, create a simple grid to show the pooling operation
grid_size = 8
small_grid = feature_map[:grid_size, :grid_size]
# Create the visualization
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
# Show the input grid
im = axs[0].imshow(small_grid, cmap='viridis')
axs[0].set_title("Input Region")
plt.colorbar(im, ax=axs[0])
# Draw grid lines
for i in range(grid_size+1):
axs[0].axhline(i-0.5, color='white', linewidth=0.5)
axs[0].axvline(i-0.5, color='white', linewidth=0.5)
# Highlight pooling windows
window_starts = list(range(0, grid_size, pool_size))
for i in window_starts:
for j in window_starts:
rect = plt.Rectangle((j-0.5, i-0.5), pool_size, pool_size,
fill=False, edgecolor='yellow', linewidth=2)
axs[0].add_patch(rect)
# Add values to cells
for i in range(grid_size):
for j in range(grid_size):
text = axs[0].text(j, i, f"{small_grid[i, j]:.2f}",
ha="center", va="center", color="w", fontsize=8)
# Show the pooling operation
axs[1].axis('off')
axs[1].set_title("Pooling Operation")
# Draw arrows from windows to results
pooled_shape = (grid_size + pool_size - 1) // pool_size
output_grid = np.zeros((pooled_shape, pooled_shape))
mid_x = grid_size / 2
arrow_length = 2
# Create descriptive text for the pooling operation
if pooling_type == "Max Pooling":
pool_op_text = "Max Pooling takes the maximum value from each highlighted window"
else:
pool_op_text = "Average Pooling takes the average of all values in each highlighted window"
axs[1].text(0.5, 0.5, pool_op_text, ha='center', va='center', wrap=True, fontsize=12)
# Show the output grid
axs[2].imshow(pooled_result[:pooled_shape, :pooled_shape], cmap='plasma')
axs[2].set_title("Output After Pooling")
# Draw grid lines
for i in range(pooled_shape+1):
axs[2].axhline(i-0.5, color='white', linewidth=0.5)
axs[2].axvline(i-0.5, color='white', linewidth=0.5)
# Add values to cells
for i in range(pooled_shape):
for j in range(pooled_shape):
text = axs[2].text(j, i, f"{pooled_result[i, j]:.2f}",
ha="center", va="center", color="w", fontsize=10)
plt.tight_layout()
st.pyplot(fig)
# 3D visualization to show the effect of pooling
st.subheader("3D Visualization of Pooling Effect")
x1 = np.arange(0, feature_map.shape[1])
y1 = np.arange(0, feature_map.shape[0])
x1_mesh, y1_mesh = np.meshgrid(x1, y1)
x2 = np.arange(0, pooled_result.shape[1])
y2 = np.arange(0, pooled_result.shape[0])
x2_mesh, y2_mesh = np.meshgrid(x2, y2)
# Scaling factor to make the pooled result align with the original
scale_factor = feature_map.shape[0] / pooled_result.shape[0]
# Create the 3D visualization with Plotly
fig = go.Figure()
# Add the surface for feature map
fig.add_trace(go.Surface(
z=feature_map,
x=x1_mesh,
y=y1_mesh,
colorscale='Viridis',
opacity=0.8,
showscale=False,
name="Before Pooling"
))
# Add the upscaled pooled result
pooled_upscaled = np.repeat(np.repeat(pooled_result, int(scale_factor), axis=0), int(scale_factor), axis=1)
x_upscaled = np.arange(0, pooled_upscaled.shape[1])
y_upscaled = np.arange(0, pooled_upscaled.shape[0])
x_up_mesh, y_up_mesh = np.meshgrid(x_upscaled, y_upscaled)
# Only show the upscaled result to the size of the original
show_size_x = min(pooled_upscaled.shape[1], feature_map.shape[1])
show_size_y = min(pooled_upscaled.shape[0], feature_map.shape[0])
fig.add_trace(go.Surface(
z=pooled_upscaled[:show_size_y, :show_size_x] + 0.05, # Slight offset for visibility
x=x_up_mesh[:show_size_y, :show_size_x],
y=y_up_mesh[:show_size_y, :show_size_x],
colorscale='Plasma',
opacity=0.6,
showscale=True,
colorbar=dict(title="After Pooling"),
name="After Pooling"
))
fig.update_layout(
title=f"Effect of {pooling_type} (pool_size={pool_size}, stride={stride})",
scene=dict(
xaxis_title='X',
yaxis_title='Y',
zaxis_title='Activation Value',
camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
),
width=800,
height=600,
margin=dict(l=0, r=0, b=0, t=40)
)
st.plotly_chart(fig)
# Comparison of pooling types
st.subheader("Comparing Pooling Types")
st.markdown("""
Different pooling types preserve different aspects of the feature maps.
Here's a comparison of Max Pooling and Average Pooling on the same input:
""")
# Apply both pooling types
max_pooled = apply_pooling(feature_map, "max", pool_size, stride)
avg_pooled = apply_pooling(feature_map, "avg", pool_size, stride)
# Create comparison visualization
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(feature_map, cmap='viridis')