-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradient_lesson.py
More file actions
1554 lines (1292 loc) · 56.5 KB
/
Copy pathgradient_lesson.py
File metadata and controls
1554 lines (1292 loc) · 56.5 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 plotly.express as px
import sympy as sp
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from derivative_examples import DERIVATIVE_RULES, PRACTICE_PROBLEMS
# Initialize session state for page navigation if it doesn't exist
if "current_page" not in st.session_state:
st.session_state["current_page"] = "Welcome"
# Set page config
st.set_page_config(page_title="Gradient Learning Module", layout="wide")
# יצירת תפריט ניווט
st.sidebar.title("Gradient Learning Module")
page = st.sidebar.radio("Select a chapter:", [
"Welcome", "Introduction", "Derivatives Basics", "Gradient Explanation",
"Gradient Visualization", "Gradient Applications", "Quiz"],
index=[
"Welcome", "Introduction", "Derivatives Basics", "Gradient Explanation",
"Gradient Visualization", "Gradient Applications", "Quiz"
].index(st.session_state["current_page"]))
# Update current_page based on radio selection
st.session_state["current_page"] = page
# Add this helper function at the top of your file, after imports
def add_navigation_buttons(prev_page=None, next_page=None):
col1, col2 = st.columns([1,1])
with col1:
if prev_page:
if st.button(f"← Back to {prev_page}"):
st.session_state["current_page"] = prev_page
st.rerun()
with col2:
if next_page:
button_text = "Take Quiz" if next_page == "Quiz" else f"Next: {next_page} →"
if st.button(button_text):
st.session_state["current_page"] = next_page
st.rerun()
# Helper function to get derivative string
def get_derivative_string(func_choice):
derivatives = {
"f(x) = x²": "f'(x) = 2x",
"f(x) = x³": "f'(x) = 3x²",
"f(x) = sin(x)": "f'(x) = cos(x)",
"f(x) = e^x": "f'(x) = e^x",
"f(x) = ln(x)": "f'(x) = 1/x"
}
return derivatives.get(func_choice, "")
if st.session_state["current_page"] == "Welcome":
st.title("Welcome to the Gradient Learning Module! 👋")
st.markdown("""
### Start Your Journey into Understanding Gradients
This interactive module will help you understand the concept of gradients from the ground up.
#### The Big Picture
For a function f(x₁, x₂, ..., xₙ), the gradient is a vector of all partial derivatives:
$$
\\nabla f = \\left(\\frac{\\partial f}{\\partial x_1}, \\frac{\\partial f}{\\partial x_2}, ..., \\frac{\\partial f}{\\partial x_n}\\right)
$$
Don't worry if this looks complicated - we'll break it down step by step!
#### What You'll Learn:
1. 📚 Basic concepts and intuition behind gradients
2. 📐 How to calculate derivatives and partial derivatives
3. 🎯 Understanding gradient direction and magnitude
4. 💻 Real-world applications in machine learning and optimization
#### How to Use This Module:
- Navigate through sections using the sidebar menu
- Try the interactive examples in each section
- Test your knowledge with the final quiz
- Take your time to understand each concept before moving forward
#### Prerequisites:
- Basic understanding of functions
- Familiarity with basic algebra
- Curiosity to learn! 🚀
Ready to begin? Click 'Next' to start with the Introduction!
""")
add_navigation_buttons(next_page="Introduction")
elif st.session_state["current_page"] == "Introduction":
st.title("Introduction to Gradient")
# Add mountain climbing GIF in a column to control its size
col1, col2, col3 = st.columns([1,2,1])
with col2:
st.image("images/hiker_gradient.gif", use_container_width=True)
st.markdown("""
## What is a Gradient?
The **gradient** is a vector that represents the direction and rate of the steepest ascent of a scalar function.
### General Form
For any function with n variables f(x₁, x₂, ..., xₙ), the gradient is defined as:
$$
\\nabla f = \\left(\\frac{\\partial f}{\\partial x_1}, \\frac{\\partial f}{\\partial x_2}, ..., \\frac{\\partial f}{\\partial x_n}\\right)
$$
### Special Case: Two Variables
For the common case of a function f(x, y) with two variables:
$$
\\nabla f = \\left(\\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}\\right)
$$
""")
st.markdown("""
### Intuitive Example
Imagine you are hiking on this mountain:
- Your **altitude** is given by a function **f(x, y)**.
- The **gradient** tells you which direction is the steepest ascent.
- If you want to descend as quickly as possible, go **opposite to the gradient**.
### Applications of Gradient
- **Mathematics & Physics** – Understanding spatial changes of functions.
- **Computer Graphics** – Adjusting shading and lighting in 3D models.
- **Machine Learning** – Used in **Gradient Descent** to optimize models.
### Summary
✅ The gradient is a powerful mathematical tool.\n
✅ It points in the direction of the greatest change.\n
✅ It has applications in **machine learning, physics, and optimization**.
### Next Step
To understand how gradients are computed, we need to review **partial derivatives**.
""")
# Add collapsible quiz section
with st.expander("### Quick Check ✍️", expanded=False):
st.markdown("Let's test your understanding of the basic gradient concepts:")
# Quiz questions with empty default state
q1 = st.radio(
"1. What does the gradient represent?",
["The average rate of change",
"The direction of steepest descent",
"The direction of steepest ascent",
"The second derivative"],
index=None, # This makes no option selected by default
key="q1" # Unique key for the radio button
)
q2 = st.radio(
"2. For a function f(x,y), how many components does its gradient have?",
["1", "2", "3", "4"],
index=None,
key="q2"
)
q3 = st.radio(
"3. In machine learning, gradient descent moves:",
["In the direction of the gradient",
"Opposite to the direction of the gradient",
"Perpendicular to the gradient",
"None of the above"],
index=None,
key="q3"
)
if st.button("Check Your Understanding", key="check_quiz"):
if None in [q1, q2, q3]:
st.warning("Please answer all questions before checking.")
else:
score = 0
if q1 == "The direction of steepest ascent":
score += 1
st.success("Question 1: Correct! ✅")
else:
st.error("Question 1: Incorrect ❌")
if q2 == "2":
score += 1
st.success("Question 2: Correct! ✅")
else:
st.error("Question 2: Incorrect ❌")
if q3 == "Opposite to the direction of the gradient":
score += 1
st.success("Question 3: Correct! ✅")
else:
st.error("Question 3: Incorrect ❌")
st.markdown(f"### Your Score: {score}/3")
if score == 3:
st.balloons()
st.success("Perfect! You're ready to move on to the next section! 🎉")
elif score >= 2:
st.success("Good understanding! Review the concepts you missed and continue! 👍")
else:
st.info("Take some time to review the concepts above before moving forward. 📚")
add_navigation_buttons(prev_page="Welcome", next_page="Derivatives Basics")
elif st.session_state["current_page"] == "Derivatives Basics":
st.title("Derivatives - Pre-requisite for Gradient")
st.markdown("""
## Understanding Derivatives
A **derivative** measures the rate at which a function changes with respect to one of its variables.
### Definition and Interpretation
If we have a function **f(x)**, its derivative is defined as:
$$
f'(x) = \\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}
$$
This represents:
1. The instantaneous rate of change at any point
2. The slope of the tangent line at point x
3. The best linear approximation of the function near x
### Fundamental Rules of Differentiation
""")
# Create tabs for different rule categories
rules_tab, examples_tab, practice_tab = st.tabs(["Rules", "Examples", "Practice"])
with rules_tab:
st.markdown("""
### Basic Rules & Common Functions
$$
\\begin{align*}
& \\textbf{Power:} & \\frac{d}{dx} x^n &= nx^{n-1} & & \\textbf{Exp/Log:} & \\frac{d}{dx}e^x &= e^x & \\frac{d}{dx}\\ln x &= \\frac{1}{x} \\\\[0.7em]
& \\textbf{Product:} & \\frac{d}{dx}[fg] &= f'g + fg' & & \\textbf{Trig:} & \\frac{d}{dx}\\sin x &= \\cos x & \\frac{d}{dx}\\cos x &= -\\sin x \\\\[0.7em]
& \\textbf{Quotient:} & \\frac{d}{dx}\\frac{f}{g} &= \\frac{f'g - fg'}{g^2} \\\\[0.7em]
& \\textbf{Chain:} & \\frac{d}{dx}f(g(x)) &= f'(g(x))g'(x)
\\end{align*}
$$
""")
with examples_tab:
selected_rule = st.selectbox(
"Select a rule to see examples:",
list(DERIVATIVE_RULES.keys())
)
st.markdown("### Examples:")
for example in DERIVATIVE_RULES[selected_rule]["examples"]:
st.markdown(rf"""
$$
\frac{{d}}{{dx}}({example['input']}) = {example['output']}
$$
""")
with practice_tab:
st.markdown("### Practice Problems")
st.markdown("Click any problem tile to see its solution. Click again to close.")
# Initialize problem page in session state if not exists
if 'problem_page' not in st.session_state:
st.session_state.problem_page = 0
# Calculate total number of pages
total_pages = (len(PRACTICE_PROBLEMS) + 5) // 6 # Ceiling division
# Display current set of 6 problems (2 rows of 3)
start_idx = st.session_state.problem_page * 6
for row in range(2): # 2 rows
cols = st.columns(3) # 3 columns per row
for col in range(3): # Fill each column
prob_idx = start_idx + row * 3 + col
if prob_idx < len(PRACTICE_PROBLEMS):
problem = PRACTICE_PROBLEMS[prob_idx]
with cols[col]:
with st.expander(f"Problem {prob_idx + 1}:\nf(x) = ${problem['function']}$", expanded=False):
st.latex(rf"\frac{{d}}{{dx}}({problem['function']}) = {problem['solution']}")
st.markdown(f"**Explanation:**\n{problem['explanation']}")
# Navigation buttons with compact layout
col1, col2, col3, col4 = st.columns([8, 1, 1, 1])
# Empty column for spacing
with col1:
st.write("")
# Previous button
with col2:
if st.session_state.problem_page > 0:
if st.button("← Prev", use_container_width=True):
st.session_state.problem_page -= 1
st.rerun()
# Page number
with col3:
st.markdown(f"<div style='text-align: center; margin-top: 5px;'>{st.session_state.problem_page + 1}/{total_pages}</div>", unsafe_allow_html=True)
# Next button
with col4:
if st.session_state.problem_page < total_pages - 1:
if st.button("Next →", use_container_width=True):
st.session_state.problem_page += 1
st.rerun()
st.markdown("### Interactive Visualization")
# Add function selector in a smaller column
col1, col2, col3 = st.columns([1,2,1])
with col1:
function_choice = st.selectbox(
"Select a function:", # Shortened label
["f(x) = x²",
"f(x) = x³",
"f(x) = sin(x)",
"f(x) = e^x",
"f(x) = ln(x)"],
index=0
)
# Display the selected function and its derivative
st.markdown("""
- Derivative: """ + get_derivative_string(function_choice) + """
""")
# Create interactive plot with slider
x_point = st.slider("Select x position", min_value=-2.0, max_value=2.0, value=0.0, step=0.1)
# Calculate function values based on selection
X = np.linspace(-2, 2, 100)
if function_choice == "f(x) = x²":
Y = X**2
dY = 2*X
y_point = x_point**2
derivative_at_point = 2 * x_point
elif function_choice == "f(x) = x³":
Y = X**3
dY = 3*(X**2)
y_point = x_point**3
derivative_at_point = 3 * (x_point**2)
elif function_choice == "f(x) = sin(x)":
Y = np.sin(X)
dY = np.cos(X)
y_point = np.sin(x_point)
derivative_at_point = np.cos(x_point)
elif function_choice == "f(x) = e^x":
Y = np.exp(X)
dY = np.exp(X)
y_point = np.exp(x_point)
derivative_at_point = np.exp(x_point)
else: # ln(x)
# Adjust domain for ln(x) since it's only defined for x > 0
X = np.linspace(0.1, 2, 100)
Y = np.log(X)
dY = 1/X
y_point = np.log(max(x_point, 0.1))
derivative_at_point = 1/max(x_point, 0.1)
x_point = max(x_point, 0.1) # Ensure x is positive for ln(x)
# Create points for tangent line
x_tangent = np.array([x_point - 0.5, x_point + 0.5])
y_tangent = derivative_at_point * (x_tangent - x_point) + y_point
# Create subplots
fig = go.Figure()
fig = make_subplots(rows=2, cols=1,
subplot_titles=(
f"Function {function_choice} with tangent line (slope: {derivative_at_point:.2f})",
f"Derivative d/dx({function_choice})"
))
# Add original function to first subplot
fig.add_trace(
go.Scatter(x=X, y=Y, mode='lines', name=function_choice, line=dict(color='blue')),
row=1, col=1
)
# Add tangent line to first subplot (now solid)
fig.add_trace(
go.Scatter(x=x_tangent, y=y_tangent, mode='lines',
name=f'Tangent at x={x_point}',
line=dict(color='red'),
showlegend=False), # Removed dash='dash'
row=1, col=1
)
# Add point on original function
fig.add_trace(
go.Scatter(x=[x_point], y=[y_point], mode='markers',
name=f'x = {x_point}',
marker=dict(color='red', size=10)),
row=1, col=1
)
# Add derivative function to second subplot
fig.add_trace(
go.Scatter(x=X, y=dY, mode='lines',
name=f"d/dx({function_choice}) = {derivative_at_point:.2f}",
line=dict(color='orange'),
showlegend=False),
row=2, col=1
)
# Add horizontal dotted line at derivative value
fig.add_trace(
go.Scatter(x=[-2, 2], y=[derivative_at_point, derivative_at_point],
mode='lines',
name=f"d/dx({function_choice}) = {derivative_at_point:.2f}",
line=dict(color='red', dash='dash')),
row=2, col=1
)
# Add point on derivative
fig.add_trace(
go.Scatter(x=[x_point], y=[derivative_at_point],
mode='markers',
name='Derivative Value',
marker=dict(color='red', size=10),
showlegend=False),
row=2, col=1
)
# Update layout
fig.update_layout(
height=700,
showlegend=True,
title_text="Function and its Derivative"
)
# Update axes labels
fig.update_xaxes(title_text="x", row=1, col=1)
fig.update_xaxes(title_text="x", row=2, col=1)
fig.update_yaxes(title_text="f(x)", row=1, col=1)
fig.update_yaxes(title_text="f'(x)", row=2, col=1)
st.plotly_chart(fig, use_container_width=True)
add_navigation_buttons(prev_page="Introduction", next_page="Gradient Explanation")
elif st.session_state["current_page"] == "Gradient Explanation":
st.title("Detailed Explanation of Gradient")
# Create tabs for different sections
theory_tab, examples_tab, practice_tab, calculator_tab = st.tabs(["Theory", "Examples", "Practice", "Calculator"])
with theory_tab:
st.markdown(r"""
## 🧠 Mathematical Foundation of Gradients
### 📐 Definition
For a multivariable function:
$$
f: \mathbb{R}^n \rightarrow \mathbb{R}
$$
The **gradient** is defined as:
$$
\nabla f =
\begin{pmatrix}
\frac{\partial f}{\partial x_1} \\
\frac{\partial f}{\partial x_2} \\
\vdots \\
\frac{\partial f}{\partial x_n}
\end{pmatrix}
$$
This vector tells us how the function changes in each variable direction.
""")
st.markdown(r"""
---
### 🧩 Key Theoretical Properties
1. **Directional Derivative** in the direction of a vector v (where v is a unit vector):
$$
D_{\vec{v}} f(x) = \nabla f(x) \cdot \frac{\vec{v}}{\|\vec{v}\|}
$$
This represents the rate of change of the function f in the direction of v, providing insights into how the function behaves along different paths.
2. **Maximum Rate of Change**:
The gradient vector ∇f(x) indicates the direction of the steepest ascent, and its magnitude ||∇f(x)|| gives the maximum rate of change at that point:
$$
\|\nabla f(x)\| = \max_{\|\vec{v}\| = 1} D_{\vec{v}} f(x)
$$
This property is crucial in optimization, as it helps identify the most efficient path to increase the function's value.
3. **Level Sets**:
At any point, the gradient is orthogonal to the level set, which is the set of points where the function takes a constant value:
$$
\nabla f(x, y) \perp \text{curve where } f(x, y) = c
$$
This orthogonality is fundamental in understanding the geometry of functions and is widely used in fields such as differential geometry and physics.
""")
st.markdown(r"""
---
### 🧮 Critical Points and Optimization
A **critical point** is a point where the gradient is zero or undefined, indicating potential local extrema or saddle points:
$$
\nabla f = 0 \quad \text{or} \quad \text{the gradient is undefined}
$$
**Classification of critical points** involves analyzing the Hessian matrix, which is the matrix of second-order partial derivatives:
- **Local Minimum**: All eigenvalues of the Hessian are positive, indicating a convex region.
- **Local Maximum**: All eigenvalues are negative, indicating a concave region.
- **Saddle Point**: Mixed signs in the eigenvalues, indicating a point of inflection.
Understanding these classifications is essential in multivariable calculus and optimization, as they provide insights into the nature of the function's behavior at critical points.
""")
st.markdown(r"""
---
### 📈 Gradient as a Directional Tool
The gradient always points in the direction of **steepest ascent**.
If you are climbing a hill described by a function \( f(x, y) \), then:
- ∇f(x, y) tells you where to go **uphill fastest**
- -∇f(x, y) leads **downhill**
- Walking **perpendicular** to the gradient → **stay on the same level**
""")
st.markdown(r"""
---
### 🔍 Example: \( f(x, y) = x^2 + y^2 \)
#### ✅ Step 1: Compute the Gradient
$$
\frac{\partial f}{\partial x} = 2x \quad , \quad
\frac{\partial f}{\partial y} = 2y
$$
So:
$$
\nabla f(x, y) = (2x, 2y)
$$
---
#### ✅ Step 2: Plug in Some Points
**Example A**:
$$
(x, y) = (1, 2) \Rightarrow \nabla f = (2, 4)
$$
**Example B**:
$$
(x, y) = (-3, 1) \Rightarrow \nabla f = (-6, 2)
$$
---
#### ✅ Step 3: What Do These Numbers Mean?
- The gradient is a **vector** showing the direction of **steepest increase**.
- For Example A:
$$
\|\nabla f\| = \sqrt{2^2 + 4^2} = \sqrt{20} \approx 4.47
$$
- For Example B:
$$
\|\nabla f\| = \sqrt{(-6)^2 + 2^2} = \sqrt{40} \approx 6.32
$$
- So:
- **B** is steeper than **A**.
- The direction shows **where to move** to climb fastest.
---
### 📏 Gradient Magnitude
The gradient's magnitude tells us how steep the function is:
$$
\|\nabla f(x, y)\| = \sqrt{ \left( \frac{\partial f}{\partial x} \right)^2 + \left( \frac{\partial f}{\partial y} \right)^2 }
$$
- A **larger value** means the function increases faster at that point.
- If the gradient is 0, the function is **flat** there (possible minimum or maximum).
""")
with examples_tab:
st.markdown("""
## Gradient Examples
### Basic Rules for Partial Derivatives
1. **Treat other variables as constants**:
When finding ∂f/∂x, treat y as a constant, and vice versa.
2. **Power Rule**:
$$\\frac{\\partial}{{\\partial x}} x^n = nx^{n-1}$$
3. **Product Rule**:
$$\\frac{\\partial}{{\\partial x}} (uv) = u\\frac{\\partial v}{\\partial x} + v\\frac{\\partial u}{\\partial x}$$
### Common Examples
""")
# Example selector
example_function = st.selectbox(
"Select an example to see its gradient:",
[
"f(x,y) = x² + y²",
"f(x,y) = x²y",
"f(x,y) = sin(x)cos(y)",
"f(x,y) = e^(x+y)",
"f(x,y) = ln(x) + y²"
]
)
examples = {
"f(x,y) = x² + y²": {
"gradient": ["2x", "2y"],
"explanation": "Each partial derivative treats the other variable as a constant. For ∂f/∂x, y² is constant; for ∂f/∂y, x² is constant."
},
"f(x,y) = x²y": {
"gradient": ["2xy", "x²"],
"explanation": "Use the product rule for ∂f/∂x. For ∂f/∂y, treat x² as a constant coefficient."
},
"f(x,y) = sin(x)cos(y)": {
"gradient": ["cos(x)cos(y)", "-sin(x)sin(y)"],
"explanation": "Use the product rule and chain rule. Note the negative sign in ∂f/∂y due to the derivative of cos(y)."
},
"f(x,y) = e^(x+y)": {
"gradient": ["e^(x+y)", "e^(x+y)"],
"explanation": "The chain rule gives us the same result for both partial derivatives since e^(x+y) is symmetric in x and y."
},
"f(x,y) = ln(x) + y²": {
"gradient": ["1/x", "2y"],
"explanation": "The partial derivatives are independent since the function is a sum. Use the natural log rule for x and power rule for y."
}
}
example = examples[example_function]
st.markdown(f"""
For {example_function}, the gradient is:
$$
\\nabla f = \\begin{{pmatrix}}
\\frac{{\\partial f}}{{\\partial x}} = {example['gradient'][0]} \\\\[1em]
\\frac{{\\partial f}}{{\\partial y}} = {example['gradient'][1]}
\\end{{pmatrix}}
$$
**Explanation**: {example['explanation']}
""")
with practice_tab:
st.markdown("""
## Practice Problems
Test your understanding of gradients with these practice problems.
Click each problem to see its solution.
""")
# Initialize practice problem state if not exists
if 'gradient_problem_page' not in st.session_state:
st.session_state.gradient_problem_page = 0
practice_problems = [
{
"function": "f(x,y) = x³ + 2xy",
"gradient": ["3x² + 2y", "2x"],
"explanation": "For ∂f/∂x, use power rule on x³ and treat y as constant in 2xy. For ∂f/∂y, treat x as constant."
},
{
"function": "f(x,y) = xy² + sin(x)",
"gradient": ["y² + cos(x)", "2xy"],
"explanation": "For ∂f/∂x, y² is a constant coefficient. For ∂f/∂y, use power rule treating x as constant."
},
{
"function": "f(x,y) = e^x cos(y)",
"gradient": ["e^x cos(y)", "-e^x sin(y)"],
"explanation": "Use product rule. Note the negative sign in ∂f/∂y from the derivative of cos(y)."
},
{
"function": "f(x,y) = ln(x²+y²)",
"gradient": ["2x/(x²+y²)", "2y/(x²+y²)"],
"explanation": "Use chain rule. The derivative of ln(u) is 1/u times the derivative of u."
},
{
"function": "f(x,y) = x²y³",
"gradient": ["2xy³", "3x²y²"],
"explanation": "Use product rule and power rule. Treat other variables as constants when taking each partial derivative."
}
]
# Display current problem
current_problem = practice_problems[st.session_state.gradient_problem_page]
with st.expander(f"Problem {st.session_state.gradient_problem_page + 1}: Find ∇f for {current_problem['function']}", expanded=True):
if st.button("Show Solution", key=f"sol_{st.session_state.gradient_problem_page}"):
st.markdown(f"""
The gradient is:
$$
\\nabla f = \\begin{{pmatrix}}
{current_problem['gradient'][0]} \\\\[1em]
{current_problem['gradient'][1]}
\\end{{pmatrix}}
$$
**Explanation**: {current_problem['explanation']}
""")
# Navigation buttons
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if st.session_state.gradient_problem_page > 0:
if st.button("← Previous Problem"):
st.session_state.gradient_problem_page -= 1
st.rerun()
with col2:
st.markdown(f"<div style='text-align: center'>Problem {st.session_state.gradient_problem_page + 1} of {len(practice_problems)}</div>", unsafe_allow_html=True)
with col3:
if st.session_state.gradient_problem_page < len(practice_problems) - 1:
if st.button("Next Problem →"):
st.session_state.gradient_problem_page += 1
st.rerun()
with calculator_tab:
st.markdown("""
### Interactive Gradient Calculator
Experiment with calculating gradients of different functions:
""")
# Interactive gradient calculator with advanced options
x, y, z = sp.symbols('x y z')
# Function input
input_function = st.text_input("Enter a function (e.g., x**2 + y**2, x*y*z):", "x**2 + y**2")
try:
expr = sp.sympify(input_function)
# Automatically detect used variables
variables = sorted(str(var) for var in expr.free_symbols)
gradient_components = []
for var in variables:
grad = sp.diff(expr, sp.Symbol(var))
gradient_components.append(grad)
# Display the gradient
gradient_expr = ' \\\\ '.join([str(comp) for comp in gradient_components])
st.markdown("""
For the function f(""" + ', '.join(variables) + ") = " + str(expr) + """:
The gradient is:
$$
\\nabla f = \\begin{pmatrix} """ + gradient_expr + """ \\end{pmatrix}
$$
""")
# Additional mathematical properties
if len(variables) == 2: # Only for 2D functions
var1, var2 = variables
val1 = st.slider(f"{var1} value", -5.0, 5.0, 0.0, 0.1)
val2 = st.slider(f"{var2} value", -5.0, 5.0, 0.0, 0.1)
# Calculate gradient magnitude at point
grad_magnitude = sp.sqrt(sum(comp**2 for comp in gradient_components))
point_values = {sp.Symbol(var1): val1, sp.Symbol(var2): val2}
magnitude_at_point = grad_magnitude.subs(point_values)
st.markdown(f"""
At point ({val1}, {val2}):
Gradient magnitude: {magnitude_at_point:.2f}
""")
except Exception as e:
st.error(f"Please enter a valid mathematical expression. Error: {str(e)}")
add_navigation_buttons(prev_page="Derivatives Basics", next_page="Gradient Visualization")
elif st.session_state["current_page"] == "Gradient Visualization":
st.title("Visualizing Gradients in Multiple Dimensions")
st.markdown("""
### Understanding Gradient Fields
A gradient field is a visual representation of gradients at different points in space.
The arrows in the field indicate:
- **Direction**: Where the function increases most rapidly
- **Length**: How steep the increase is at that point
### Interactive Gradient Field Visualization
Select a function to visualize its gradient field:
""")
# Function selection
function_choice = st.selectbox(
"Choose a function:",
["f(x,y) = x² + y²",
"f(x,y) = sin(x)cos(y)",
"f(x,y) = x² - y²",
"f(x,y) = e^(-x² - y²)"],
index=0
)
# Create grid of points
x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
# Calculate function values and gradients based on selection
if function_choice == "f(x,y) = x² + y²":
Z = X**2 + Y**2
U = 2*X # dx
V = 2*Y # dy
title = "Gradient Field of f(x,y) = x² + y²"
elif function_choice == "f(x,y) = sin(x)cos(y)":
Z = np.sin(X) * np.cos(Y)
U = np.cos(X) * np.cos(Y) # dx
V = -np.sin(X) * np.sin(Y) # dy
title = "Gradient Field of f(x,y) = sin(x)cos(y)"
elif function_choice == "f(x,y) = x² - y²":
Z = X**2 - Y**2
U = 2*X # dx
V = -2*Y # dy
title = "Gradient Field of f(x,y) = x² - y²"
else: # e^(-x² - y²)
Z = np.exp(-X**2 - Y**2)
U = -2*X*np.exp(-X**2 - Y**2) # dx
V = -2*Y*np.exp(-X**2 - Y**2) # dy
title = "Gradient Field of f(x,y) = e^(-x² - y²)"
# Create tabs for different visualizations
contour_tab, field_tab, surface_tab = st.tabs(["Contour Plot", "Gradient Field", "3D Surface"])
with contour_tab:
st.markdown("""
### Contour Plot with Gradient Vectors
The contour lines show points of equal height (level curves).
The gradient vectors are always perpendicular to these contour lines.
""")
fig = go.Figure()
# Add contour plot
fig.add_trace(go.Contour(
x=x, y=y, z=Z,
colorscale='Viridis',
showscale=True,
name='Function Value'
))
# Add gradient vectors using quiver plot
skip = 2 # Show fewer arrows for clarity
# Normalize vectors for better visualization
magnitudes = np.sqrt(U**2 + V**2)
max_magnitude = np.max(magnitudes)
scale = 0.2 # Scale factor for arrow length
for i in range(0, len(x), skip):
for j in range(0, len(y), skip):
# Starting point of arrow
x_start = X[i,j]
y_start = Y[i,j]
# Calculate arrow end point
magnitude = magnitudes[i,j]
if magnitude > 0: # Avoid division by zero
dx = U[i,j] / magnitude * scale
dy = V[i,j] / magnitude * scale
else:
dx = dy = 0
# Add arrow
fig.add_trace(go.Scatter(
x=[x_start, x_start + dx],
y=[y_start, y_start + dy],
mode='lines',
line=dict(color='red', width=1),
showlegend=False
))
# Add arrowhead
fig.add_trace(go.Scatter(
x=[x_start + dx],
y=[y_start + dy],
mode='markers',
marker=dict(
symbol='triangle-up',
angle=np.arctan2(dy, dx) * 180 / np.pi - 90,
size=8,
color='red'
),
showlegend=False
))
# Add a single legend entry for gradient vectors
fig.add_trace(go.Scatter(
x=[None],
y=[None],
mode='lines+markers',
name='Gradient Vectors',
line=dict(color='red'),
marker=dict(symbol='triangle-up', color='red')
))
fig.update_layout(
title=title,
width=700,
height=600,
xaxis=dict(range=[-2.2, 2.2]),
yaxis=dict(range=[-2.2, 2.2]),
xaxis_title='x',
yaxis_title='y'
)
st.plotly_chart(fig, use_container_width=True)
with field_tab:
st.markdown("""
### Pure Gradient Field
This visualization shows just the gradient vectors, helping you understand
the direction and magnitude of steepest increase at each point.
The color and length of each arrow represents the gradient magnitude.
""")
fig = go.Figure()
# Create gradient field using arrows
skip = 2
# Normalize vectors for better visualization
magnitudes = np.sqrt(U**2 + V**2)
max_magnitude = np.max(magnitudes)
scale = 0.2 # Scale factor for arrow length
# Create a colormap function
def get_color(magnitude):
# Convert magnitude to a color using viridis colormap
# Returns color in rgb format
norm_magnitude = magnitude / max_magnitude
return f'rgb({int(255 * (1-norm_magnitude))}, {int(255 * norm_magnitude)}, 255)'
for i in range(0, len(x), skip):
for j in range(0, len(y), skip):
# Starting point of arrow
x_start = X[i,j]
y_start = Y[i,j]
# Calculate arrow end point
magnitude = magnitudes[i,j]
if magnitude > 0: # Avoid division by zero
dx = U[i,j] / magnitude * scale * magnitude/max_magnitude
dy = V[i,j] / magnitude * scale * magnitude/max_magnitude
else:
dx = dy = 0
# Get color based on magnitude
arrow_color = get_color(magnitude)
# Add arrow shaft
fig.add_trace(go.Scatter(
x=[x_start, x_start + dx],
y=[y_start, y_start + dy],
mode='lines',
line=dict(
color=arrow_color,
width=2
),
showlegend=False
))
# Add arrowhead
fig.add_trace(go.Scatter(
x=[x_start + dx],
y=[y_start + dy],
mode='markers',
marker=dict(
symbol='triangle-up',