forked from BrentScarff/Backprop-Animation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnn_backprop.py
2258 lines (1961 loc) · 83.3 KB
/
nn_backprop.py
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
from manimlib.imports import *
import numpy as np
class Network(object):
# This class is from 3B1B and copyright 3Blue1Brown LLC
# https://github.com/3b1b/manim/blob/master/from_3b1b/old/nn/network.py
# I have made some minor modifications, mainly removing things I didn't
# need.
def __init__(self, sizes, non_linearity = "sigmoid"):
"""The list ``sizes`` contains the number of neurons in the
respective layers of the network. For example, if the list
was [2, 3, 1] then it would be a three-layer network, with the
first layer containing 2 neurons, the second layer 3 neurons,
and the third layer 1 neuron. The biases and weights for the
network are initialized randomly, using a Gaussian
distribution with mean 0, and variance 1. Note that the first
layer is assumed to be an input layer, and by convention we
won't set any biases for those neurons, since biases are only
ever used in computing the outputs from later layers."""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)+0.3
for x, y in zip(sizes[:-1], sizes[1:])]
if non_linearity == "sigmoid":
self.non_linearity = sigmoid
#self.d_non_linearity = sigmoid_prime
elif non_linearity == "ReLU":
self.non_linearity = ReLU
#self.d_non_linearity = ReLU_prime
else:
raise Exception("Invalid non_linearity")
def get_activation_of_all_layers(self, input_a, n_layers = None):
if n_layers is None:
n_layers = self.num_layers
activations = [input_a.reshape((input_a.size, 1))]
#for bias, weight in zip(self.biases[:n_layers], self.weights[:n_layers]):
for bias, weight in zip(self.biases, self.weights):
last_a = activations[-1]
new_a = self.non_linearity(np.dot(weight, last_a) + bias)
new_a = new_a.reshape((new_a.size, 1))
activations.append(new_a)
return activations
#### Miscellaneous functions
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
def ReLU(z):
result = np.array(z)
result[result < 0] = 0
return result
class NetworkMobject(VGroup):
CONFIG = {
"neuron_radius" : 0.15,
"neuron_to_neuron_buff" : 3,
"layer_to_layer_buff" : LARGE_BUFF,
"neuron_stroke_color" : BLUE,
"neuron_stroke_width" : 3,
"neuron_fill_color" : GREEN,
"edge_color" : WHITE, #DARKER_GREY,
"edge_stroke_width" : 2,
"edge_propogation_color" : YELLOW_E,
"edge_propogation_time" : 1,
"max_shown_neurons" : 16,
"brace_for_large_layers" : True,
"average_shown_activation_of_large_layer" : True,
"include_output_labels" : False,
"network_calculations" : True
}
def __init__(self, neural_network, **kwargs):
VGroup.__init__(self, **kwargs)
self.neural_network = neural_network
self.layer_sizes = neural_network.sizes
self.add_neurons()
self.add_edges()
if self.network_calculations:
self.add_bias()
self.add_bias_edges()
self.add_outputs()
self.add_output_edges()
def add_neurons(self):
layers = VGroup(*[
self.get_layer(size)
for size in self.layer_sizes
])
layers.arrange(RIGHT, buff=self.layer_to_layer_buff)
self.layers = layers
self.add(self.layers)
if self.include_output_labels:
self.add_output_labels()
def add_outputs(self):
outputs = VGroup(*[
self.get_layer(self.layer_sizes[-1]),
self.get_layer(size=1)
])
outputs.move_to(self.layers[-1])
# add 2*self.neuron_radius to make spacing equal
outputs.shift(RIGHT*(self.layer_to_layer_buff))
outputs[-1].shift(RIGHT*(self.layer_to_layer_buff))
self.outputs = outputs
self.add(self.outputs)
def add_bias(self):
# add bias layer neurons
bias = VGroup(*[
self.get_layer(1) for layer in self.layer_sizes[1:]
])
bias.arrange(RIGHT, buff = self.layer_to_layer_buff)
bias.move_to(self.layers[1])
# add 2*self.neuron_radius to make spacing equal
bias.shift(DOWN*1.1*(self.neuron_to_neuron_buff))
self.bias = bias
self.add(self.bias)
def expand_nodes(self, layer_index):
new_nodes = self.get_layer(self.layer_sizes[layer_index])
new_nodes.move_to(self.layers[layer_index])
self.new_nodes = new_nodes
return(new_nodes)
def get_layer(self, size):
layer = VGroup()
n_neurons = size
if n_neurons > self.max_shown_neurons:
n_neurons = self.max_shown_neurons
neurons = VGroup(*[
Circle(
radius = self.neuron_radius,
stroke_color = self.neuron_stroke_color,
stroke_width = self.neuron_stroke_width,
fill_color = self.neuron_fill_color,
fill_opacity = 0,
)
for x in range(n_neurons)
])
neurons.arrange(
DOWN, buff = self.neuron_to_neuron_buff
)
for neuron in neurons:
neuron.edges_in = VGroup()
neuron.edges_out = VGroup()
layer.neurons = neurons
layer.add(neurons)
if size > n_neurons:
dots = TexMobject("\\vdots")
dots.move_to(neurons)
VGroup(*neurons[:len(neurons) // 2]).next_to(
dots, UP, MED_SMALL_BUFF
)
VGroup(*neurons[len(neurons) // 2:]).next_to(
dots, DOWN, MED_SMALL_BUFF
)
layer.dots = dots
layer.add(dots)
if self.brace_for_large_layers:
brace = Brace(layer, LEFT)
brace_label = brace.get_tex(str(size))
layer.brace = brace
layer.brace_label = brace_label
layer.add(brace, brace_label)
return layer
def add_edges(self):
self.edge_groups = VGroup()
for l1, l2 in zip(self.layers[:-1], self.layers[1:]):
edge_group = VGroup()
for n1, n2 in it.product(l1.neurons, l2.neurons):
edge = self.get_edge(n1, n2)
edge_group.add(edge)
n1.edges_out.add(edge)
n2.edges_in.add(edge)
self.edge_groups.add(edge_group)
self.add_to_back(self.edge_groups)
def update_edges(self):
new_edge_group = VGroup()
for l1, l2 in zip(self.layers[:-1], self.layers[1:]):
edge_group = VGroup()
for n1, n2 in it.product(l1.neurons, l2.neurons):
edge = self.get_edge(n1, n2)
edge_group.add(edge)
new_edge_group.add(edge_group)
return new_edge_group
def add_bias_edges(self):
# Assumes edges run first and self.edge_groups exists.
self.bias_edge_groups = VGroup()
for l1, l2 in zip(self.bias, self.layers[1:]):
edge_group = VGroup()
for n1, n2 in it.product(l1.neurons, l2.neurons):
edge = self.get_edge(n1, n2)
edge.set_color(LIGHT_GREY)
edge.set_opacity(0.25)
edge_group.add(edge)
n1.edges_out.add(edge)
n2.edges_in.add(edge)
self.bias_edge_groups.add(edge_group)
self.add_to_back(self.bias_edge_groups)
def add_output_edges(self):
self.out_edge_groups = VGroup()
out_edge_group = VGroup()
# Add edges from the last layer to the error nodes
for n1, n2 in zip(self.layers[-1].neurons, self.outputs[0].neurons):
edge = self.get_edge(n1, n2)
n1.edges_out.add(edge)
n2.edges_in.add(edge)
n1.next = VGroup()
n1.next.add(n2)
out_edge_group.add(edge)
self.out_edge_groups.add(out_edge_group)
# Add edges from the error node to the Error Total
error_edge_group = VGroup()
for n1, n2 in zip(self.outputs[0].neurons, it.cycle(self.outputs[-1].neurons)):
edge = self.get_edge(n1, n2)
n1.edges_out.add(edge)
error_edge_group.add(edge)
self.out_edge_groups.add(error_edge_group)
self.add_to_back(self.out_edge_groups)
def get_edge(self, neuron1, neuron2):
return Line(
neuron1.get_center(),
neuron2.get_center(),
buff = self.neuron_radius,
stroke_color = self.edge_color,
stroke_width = self.edge_stroke_width,
)
def add_arrows(self):
self.arrow_groups = VGroup()
for n1, n2 in zip(self.layers[-1].neurons, self.outputs[0].neurons):
arrow = self.get_arrow(n1, n2)
self.arrow_groups.add(arrow)
self.add_to_back(self.arrow_groups)
def get_arrow(self, neuron1, neuron2):
return Arrow(
neuron1.get_center(),
neuron2.get_center(),
buff = self.neuron_radius,
stroke_color = BLUE,
)
def get_active_layer(self, layer_index, activation_vector):
layer = self.layers[layer_index].deepcopy()
self.activate_layer(layer, activation_vector)
return layer
def activate_layer(self, layer, activation_vector):
n_neurons = len(layer.neurons)
av = activation_vector
def arr_to_num(arr):
return (np.sum(arr > 0.1) / float(len(arr)))**(1./3)
if len(av) > n_neurons:
if self.average_shown_activation_of_large_layer:
indices = np.arange(n_neurons)
indices *= int(len(av)/n_neurons)
indices = list(indices)
indices.append(len(av))
av = np.array([
arr_to_num(av[i1:i2])
for i1, i2 in zip(indices[:-1], indices[1:])
])
else:
av = np.append(
av[:n_neurons/2],
av[-n_neurons/2:],
)
for activation, neuron in zip(av, layer.neurons):
neuron.set_fill(
color = self.neuron_fill_color,
opacity = activation
)
return layer
def activate_layers(self, input_vector):
activations = self.neural_network.get_activation_of_all_layers(input_vector)
for activation, layer in zip(activations, self.layers):
self.activate_layer(layer, activation)
def get_edge_propogation_animations(self, index, bias=False):
if bias:
edge_group_copy = self.bias_edge_groups[index].copy()
else:
edge_group_copy = self.edge_groups[index].copy()
edge_group_copy.set_stroke(
self.edge_propogation_color,
width = 1.5*self.edge_stroke_width
)
return [ShowCreationThenDestruction(
edge_group_copy,
run_time = self.edge_propogation_time,
lag_ratio = 0.5
)]
# class TexMobject(TexMobject):
# #Updating TexMobject color config
# CONFIG = {
# "color": DARKER_GREY,
# "background_stroke_color": GREY,
# #"fill_color": BLACK
# }
# class TextMobject(TextMobject):
# #Updating TextMobjet color
# CONFIG = {
# "color": DARKER_GREY,
# "background_stroke_color": GREY,
# }
class NetworkScene(Scene):
CONFIG = {
"layer_sizes" : [2, 2, 2],
"label_scale" : 0.75,
"network_mob_config" : {},
#"camera_config":{"background_color": WHITE}
}
# The Scene class __init__ method calls this setup method
def setup(self):
self.add_network()
def add_network(self):
self.network = Network(sizes = self.layer_sizes)
self.network_mob = NetworkMobject(
self.network,
**self.network_mob_config
)
self.add(self.network_mob)
class Intro(NetworkScene):
color = color_gradient([BLUE_B, YELLOW_B, BLUE_B], 5)
CONFIG = {
"layer_sizes" : [8, 6, 6, 4],
"network_mob_config" : {
"neuron_to_neuron_buff" : SMALL_BUFF,
"layer_to_layer_buff" : 1.5,
"edge_propogation_time" : 0.4,
"neuron_fill_color" : BLUE_A,
"edge_color" : WHITE, #GREY,
"edge_propogation_color" : color,
"network_calculations" : False
},
#"camera_config":{"background_color": WHITE}
}
def setup(self):
NetworkScene.setup(self)
self.remove(self.network_mob)
def construct(self):
self.show_words()
self.wait(2)
self.show_network()
self.transform_network()
def show_words(self):
self.words = TextMobject("What is a Neural Network?")
self.words.scale(1.5)
self.words.set_color(BLUE)
self.play(FadeIn(self.words))
def show_network(self):
network_mob = self.network_mob
flat_layers = VGroup(*it.chain(*network_mob.layers))
self.play(
ReplacementTransform(
self.words,
VGroup(flat_layers)
),
)
self.play(ShowCreation(
network_mob.edge_groups,
lag_ratio = 0.5,
run_time = 2,
rate_func=linear,
))
in_vect = np.random.random(self.network.sizes[0])
network_mob.activate_layers(in_vect)
def transform_network(self):
#I should have broken this up more...
big_network = Network(sizes = [15, 12, 14, 12, 8, 6])
self.big_network_mob = NetworkMobject(
big_network,
**self.network_mob_config
)
small_net = self.network_mob
big_net = self.big_network_mob
self.play(ReplacementTransform(small_net, big_net))
self.network = big_network
self.add(self.big_network_mob)
in_vect = np.random.random(big_network.sizes[0])*(1-0.4) + 0.4
big_net.activate_layers(in_vect)
edges=VGroup()
self.edges = VGroup()
for i, edge_group in enumerate(self.big_network_mob.edge_groups):
layer = i
for edge in edge_group:
edges.add(edge)
edge.layer = i
self.edges = edges
neurons = VGroup(*it.chain(*[l.neurons for l in self.big_network_mob.layers]))
for neuron in neurons:
neuron.colors = [BLUE_A, BLUE_A, WHITE, BLUE_B, BLUE_B]
random.shuffle(neuron.colors)
neuron.cycle_time = 0.5*(1 + random.random())
neuron.sign = 1
self.step = 5
segments = VGroup()
self.sign=1
self.internal_time=0
color = color_gradient([GRAY, BLUE_B, WHITE, BLUE_B, GRAY], 5)
for edge in edges[::self.step]:
segment = edge.copy().scale_in_place(0.2)
segment.set_stroke(color, 1.5*self.big_network_mob.edge_stroke_width)
segments.add(segment)
segment.layer = edge.layer
segment.cycle_time = 0.5
segments.set_opacity(0)
self.opacity = 1
num_layers = len(big_network.sizes)
total_time = segment.cycle_time * num_layers
layer_time = segment.cycle_time
def edge_activation(segments, dt):
self.internal_time += dt
for i, segment in enumerate(segments):
edge = edges[i*self.step]
seg_scale = 0.2/(segment.get_length()/edge.get_length())
segment.scale_in_place(seg_scale)
segment.set_angle(edge.get_angle())
if self.internal_time < total_time: #Forward pass
start_time = segment.cycle_time*segment.layer#*i/15
if self.internal_time > start_time:
segment.set_opacity(self.opacity)
alpha = np.fmod(self.internal_time-start_time,segment.cycle_time)/segment.cycle_time
segment.move_to(edge.point_from_proportion(max(alpha,0.)))
else: #Backward pass
segment.set_opacity(0)
start_time = total_time + segment.cycle_time*(num_layers - 1.5 - segment.layer)
if self.internal_time > start_time:
segment.set_opacity(self.opacity)
alpha = np.fmod(self.internal_time-start_time,segment.cycle_time)/segment.cycle_time
segment.move_to(edge.point_from_proportion(min(1-alpha,1.)))
def neuron_activation(neurons, layer, layer_size):
for neuron in neurons[:layer_size]:
t = (self.internal_time)/neuron.cycle_time
low_n = int(t)%len(neuron.colors)
high_n = int(t+1)%len(neuron.colors)
alpha = ((self.internal_time)%neuron.cycle_time)/neuron.cycle_time
color = interpolate_color(neuron.get_color(), neuron.colors[high_n], alpha)
neuron.set_fill(color)
neuron.set_stroke(color, opacity=alpha)
def forward_activation(neurons, dt):
last_layer = 0
for layer, layer_size in enumerate(big_network.sizes):
if self.internal_time > layer*layer_time:
neuron_activation(neurons, layer, layer_size+last_layer)
last_layer += layer_size
def reverse_activation(neurons, dt):
last_layer = 0
for layer, layer_size in enumerate(big_network.sizes[::-1]):
if self.internal_time > total_time+2*dt + layer*layer_time:
neuron_activation(neurons, layer, layer_size+last_layer)
last_layer += layer_size
learning_question = TextMobject("How Does a Network Learn?")
learning_question.set_color(BLUE_B)
learning_question.to_edge(UP)
segments.add_updater(edge_activation)
neurons.add_updater(forward_activation)
self.add(segments, neurons)
self.play(Write(learning_question), run_time=1)
self.wait(total_time-1)
neurons.remove_updater(forward_activation)
reverse_neurons = neurons[::-1]
reverse_neurons.add_updater(reverse_activation)
self.add(reverse_neurons)
self.wait(total_time-1)
self.play(FadeOut(learning_question))
direction = [UP, DOWN, RIGHT, LEFT, UR, DL, UL, DR]
def update_neurons(neurons, dt):
new_neurons = VGroup()
random.seed(44)
for i, n1 in enumerate(neurons):
vel = 2*random.choice(direction)
rot = 0.7
#add this back in if want neurons to bounce around
#if n1.is_off_screen():
# n1.sign = -1
shift_neuron1 = n1.shift(n1.sign*dt*vel)
if i < len(neurons)-2:
shift_neuron1.rotate(n1.sign*rot*dt, about_point=neurons[i+2].get_center())
else:
shift_neuron1.rotate(n1.sign*rot*dt, about_point=neurons[i-1].get_center())
new_neurons.add(shift_neuron1)
def update_edges(network, dt):
new_edges = network.update_edges()
old_net = VGroup(*network.edge_groups)
new_net = VGroup(*new_edges)
old_net.become(new_net)
big_net.add_updater(update_edges)
neurons.add_updater(update_neurons)
for segment in segments:
segment.cycle_time = 1.2 + 2*random.random()
self.add(neurons, big_net, segments, reverse_neurons)
self.wait(3)
big_net.clear_updaters()
neurons.remove_updater(update_neurons)
self.opacity=0.6
segments.set_opacity(self.opacity)
self.play(self.big_network_mob.fade, 0.5, run_time=2)
self.wait(1)
self.add_equations()
back_prop = TextMobject("BACKPROPAGATION \\\\ A VISUAL WALKTHROUGH")
author = TextMobject("by Brent Scarff")
author.scale(0.6)
author.next_to(back_prop, DOWN, aligned_edge=RIGHT)
self.remove(segments)
flat_edges = VGroup(*it.chain(*self.big_network_mob.edge_groups))
self.play(Transform(VGroup(flat_edges), back_prop))
self.play(FadeIn(author))
self.wait(2)
def add_equations(self):
de_dw_mat = TexMobject("{\\partial E", "\\over", "\\partial W", "^{(\\ell)}}")
equals = TexMobject("=")
delta_vec = TexMobject("(\\delta^{(\\ell+1)})^{\\intercal}")
dot = TexMobject("\\cdot")
w_vec = TexMobject("W^{(\\ell+1)}")
hadamard = TexMobject("\\odot")
da_dz_vec = TexMobject("{\\partial A", "^{(\\ell)}", "\\over", "\\partial Z", "^{(\\ell)}}")
x_mat = TexMobject("X^{(\\ell-1)}")
vec_derivatives = VGroup(*[
de_dw_mat,
equals,
delta_vec,
dot,
w_vec,
hadamard.copy(),
da_dz_vec,
hadamard.copy(),
x_mat,
])
de_db = TexMobject("{\\partial E", "\\over", "\\partial B", "^{(\\ell)}}")
delta = TexMobject("\\delta^{\\ell}")
bias_eqn = VGroup(*[
de_db,
equals.copy(),
delta,
])
delta_l_eqn = VGroup(*[
delta.copy(),
equals.copy(),
delta_vec.copy(),
dot.copy(),
w_vec.copy(),
hadamard.copy(),
da_dz_vec.copy(),
])
delta_L = TexMobject("\\delta^{L}")
de_da_vec = TexMobject("{\\partial E", "\\over", "\\partial A", "^{(L)}}")
da_dz_L = TexMobject("{\\partial A", "^{(L)}", "\\over", "\\partial Z", "^{(L)}}")
delta_L_eqn = VGroup(*[
delta_L,
equals.copy(),
de_da_vec,
hadamard.copy(),
da_dz_L])
vec_derivatives.arrange(RIGHT)
vec_derivatives.set_opacity(0.5)
vec_derivatives.rotate(TAU/12)
vec_derivatives.shift(2.5*UL)
bias_eqn.arrange(RIGHT)
bias_eqn.set_opacity(0.5)
bias_eqn.rotate(-TAU/16)
bias_eqn.shift(2.8*RIGHT+1.5*DOWN)
delta_l_eqn.arrange(RIGHT)
delta_l_eqn.set_opacity(0.5)
delta_l_eqn.rotate(0.1)
delta_l_eqn.shift(1.5*UP+2*RIGHT)
delta_L_eqn.arrange(RIGHT)
delta_L_eqn.set_opacity(0.5)
delta_L_eqn.rotate(-TAU/12)
delta_L_eqn.shift(1.9*DL)
self.play(FadeIn(VGroup(vec_derivatives,
bias_eqn,
delta_l_eqn,
delta_L_eqn),
lag_ratio=0.8, run_time=4))
outlines = VGroup(*[vec_derivatives.copy(),
bias_eqn.copy(),
delta_l_eqn.copy(),
delta_L_eqn.copy()])
outlines.set_stroke(BLUE_B, opacity=0.7)
outlines.set_fill(opacity=0)
self.play(Write(outlines))
self.play(FadeOut(vec_derivatives),
FadeOut(delta_l_eqn),
FadeOut(delta_L_eqn),
FadeOut(bias_eqn),
FadeOut(outlines))
class NetworkSetup(NetworkScene):
CONFIG = {
"network_mob_config" : {
"neuron_stroke_color" : WHITE,#DARKER_GREY,
"neuron_fill_color" : GREY,
"neuron_radius" : 0.45,
"layer_to_layer_buff" : 2,
},
"label_scale" : 0.75,
"layer_sizes" : [2, 2, 2],
}
def construct(self):
self.setup_network_mob()
self.show_labels()
self.show_weights()
#self.play(FadeOut(self.error_sum))
self.insert_activations(layer_index=2)
self.insert_activations(layer_index=1)
self.rescale_network()
layer = 2
weight_indexs_2 = [[layer,1,1], [layer,1,2], [layer,2,2], [layer,2,1]]
directions = [UP,3.5*RIGHT, DOWN, 3.5*LEFT]
for weight_index, direction in zip(weight_indexs_2, directions):
self.find_derivative(weight_index)
#self.trace_back(weight_index=weight_index)
self.partial_derivative(weight_index=weight_index)
self.step_through(weight_index)
self.make_room(direction)
self.play(*self.show_col_matrix(self.de_da_terms.copy(), BLUE_B))
self.play(*self.show_col_matrix(self.da_dz_terms.copy(), YELLOW_B))
self.play(*self.show_col_matrix(self.dz_dw_terms.copy(), RED_B, matrix=True))
self.add_multipliers(
[self.column_brackets[0],
self.column_brackets[1],
self.column_brackets[2]]
)
self.write_out_formulas()
self.reset_network()
weight_index_1 = [1,1,1]
self.find_derivative(weight_index_1)
self.partial_derivative(weight_index=weight_index_1)
self.step_through(weight_index_1)
self.recall_delta()
layer_1 = 1
weight_indexs_1 = [[layer_1,1,2], [layer_1,2,2], [layer_1,2,1]]
directions_1 = [3.5*RIGHT, DOWN, 3.5*LEFT]
for i, (weight_index, direction) in enumerate(zip(weight_indexs_1, directions_1)):
if i == 2:
self.play(self.equation[-1].fade, 0.9)
self.find_derivative(weight_index)
self.partial_derivative(weight_index=weight_index)
self.step_through(weight_index)
self.delta_transform()
self.make_room(direction)
self.play(self.equation[-2].set_opacity, 1)
self.play(FadeOut(self.full_network))
self.play(*self.show_col_matrix(self.de_da_terms[-4:].copy(), BLUE_B, position=0.8*DOWN))
self.play(*self.show_col_matrix(self.da_dz_terms[-4:].copy(), YELLOW_B))
self.play(*self.show_col_matrix(self.dz_dw_terms[-4:].copy(), RED_B, matrix=True))
self.break_down_delta_l()
self.write_out_formulas_sublayers()
self.dz_da_derivative()
self.dz_dw_derivative()
self.generalize_equations()
self.play(FadeIn(self.full_network))
self.find_derivative([2,1,3], bias=True)
self.partial_derivative(weight_index=[2,1], bias=True)
self.step_through([2, 1, 3])
self.generalize_bias()
self.show_final_eqns()
def setup_network_mob(self):
self.network_mob.to_edge(LEFT, buff = LARGE_BUFF)
#self.network_mob.layers[1].neurons.shift(0.02*RIGHT)
def show_labels(self):
self.activate_layer(0)
self.activate_layer(1)
self.activate_layer(2)
self.activate_output()
# neuron_1 = 0
# neuron_2 = 1
# self.show_error(neuron_1, UP, 'bce')
# self.show_error(neuron_2, DOWN, 'mse')
def activate_layer(self, layer_index, label='a', bias=True, sublayer=False):
if sublayer:
layer = self.network_mob.layers[layer_index].sublayer
else:
layer = self.network_mob.layers[layer_index]
if layer_index > 0:
neuron_labels = VGroup(*[
TexMobject("%s^{(%d)}_%d"%(label, layer_index,d+1))
for d in range(len(layer.neurons))
])
if bias:
self.activate_bias(layer_index)
else:
neuron_labels = VGroup(*[
TexMobject("x^{(%d)}_%d"%(layer_index,d+1))
for d in range(len(layer.neurons))
])
for label, neuron in zip(neuron_labels, layer.neurons):
label.scale(0.75)
label.move_to(neuron)
neuron.label = label
self.add(neuron_labels)
if sublayer:
try:
self.sublayer_labels.add_to_back(neuron_labels)
except:
self.sublayer_labels = VGroup()
self.sublayer_labels.add_to_back(neuron_labels)
else:
try:
self.neuron_labels.add(neuron_labels)
except:
self.neuron_labels = VGroup()
self.neuron_labels.add(neuron_labels)
def activate_output(self):
layer = self.network_mob.outputs[0]
e_labels = VGroup(*[
TexMobject("e",
"^{(%d)}_%d"%(self.network_mob.neural_network.num_layers,d+1))
for d in range(len(layer.neurons))],
TexMobject("E")
)
e_labels.set_color(RED_B)
e_labels.scale(self.label_scale)
for label, neuron in zip(e_labels[:-1], layer.neurons):
#label.scale(self.label_scale)
label.move_to(neuron)
neuron.label = label
e_labels[-1].move_to(self.network_mob.outputs[-1].neurons)
self.add(e_labels)
self.e_labels = e_labels
def activate_bias(self, layer_index):
layer = self.network_mob.bias[layer_index-1]
b_labels = TexMobject("b^{(%d)}"%(layer_index))
for label, neuron in zip(b_labels, layer.neurons):
label.scale(self.label_scale)
label.move_to(neuron)
neuron.label = label
self.add(b_labels)
try:
self.b_labels.add(b_labels)
except:
self.b_labels = VGroup()
self.b_labels.add(b_labels)
def show_weights(self):
self.activate_neuron_weights(1)
self.activate_neuron_weights(2)
self.activate_bias_weights(1)
self.activate_bias_weights(2)
self.wait()
def activate_neuron_weights(self, layer_index):
layer = self.network_mob.layers[layer_index]
size_l = self.network_mob.layer_sizes[layer_index]
size_lp = self.network_mob.layer_sizes[layer_index-1]
edges = self.network_mob.edge_groups[layer_index-1]
anim_edges = self.network_mob.get_edge_propogation_animations(layer_index-1)
eps = 1e-3
w_labels = VGroup(*[
TexMobject("w^{(%d)}_{%d%d}" %(layer_index, l2, l1))
for l1, l2 in it.product(range(1, size_l+1), range(1, size_lp+1))
])
# It's easier to create a list of just the weight labels and
# a list of the labels after they've been rotated for the neural
# network
try:
self.w_labels.add(w_labels)
except:
self.w_labels = VGroup()
self.w_labels.add(w_labels)
w_labels_nn = w_labels.copy()
# Position w_labels
for w_label, edge in zip(w_labels_nn, edges):
w_label.scale(self.label_scale)
w_label.rotate(edge.get_angle())
w_label.vector = edge.get_unit_vector()
w_label.perp = rotate_vector(w_label.vector, np.pi/2)
if abs(edge.get_angle()) > eps:
w_label.shift(edge.get_center() +
1*(w_label.vector) +
0.4*(w_label.perp))
else:
w_label.shift(edge.get_center() + UP*0.4)
w_label.set_color(GREEN_D)
edge.label = w_label
# This is the neural network weight list
try:
self.w_labels_nn.add(w_labels_nn)
except:
self.w_labels_nn = VGroup()
self.w_labels_nn.add(w_labels_nn)
self.play(*anim_edges,
Write(w_labels_nn, run_time = 1)
)
def activate_bias_weights(self, layer_index):
layer = self.network_mob.layers[layer_index]
size_l = self.network_mob.layer_sizes[layer_index]
# layer_index-1 = current bias index.
edges = self.network_mob.bias_edge_groups[layer_index-1]
anim_edges = self.network_mob.get_edge_propogation_animations(layer_index-1, bias=True)
eps = 1e-3
bw_labels = VGroup(*[
TexMobject("b^{(%d)}_{%d}" %(layer_index, l1))
for l1 in range(1, size_l+1)
])
try:
self.bw_labels.add(bw_labels)
except:
self.bw_labels = VGroup()
self.bw_labels.add(bw_labels)
bw_labels_nn = bw_labels.copy()
for bw_label, edge in zip(bw_labels_nn, edges):
bw_label.scale(self.label_scale)
bw_label.rotate(edge.get_angle())
bw_label.vector = edge.get_unit_vector()
bw_label.perp = rotate_vector(bw_label.vector, np.pi/2)
if abs(edge.get_angle()) > eps:
bw_label.shift(edge.get_corner(DL) +
0.5*(bw_label.vector) +
0.2*(bw_label.perp))
else:
bw_label.shift(edge.get_center() + UP*0.4)
bw_label.set_color(BLUE)
edge.label = bw_label
# This is the neural network weight list
try:
self.bw_labels_nn.add(bw_labels_nn)
except:
self.bw_labels_nn = VGroup()
self.bw_labels_nn.add(bw_labels_nn)
self.play(*anim_edges,
Write(bw_labels_nn, run_time = 1)
)
def bce(self):
'''
Binary Cross Entropy error function label
Currently not used.
'''
# Define existing labels we will be copying and moving around
neuron_labels = VGroup(*[
self.neuron_labels[-1][0],
self.neuron_labels[-1][0]
]).copy()
neuron_labels.generate_target()
error_sum1 = VGroup()
error_sum2 = VGroup()
error_type = TextMobject("Binary Cross-Entropy")
neuron_label = neuron_labels.target
neuron_label.scale(1./0.75)
y_label = TexMobject("-","y")
y_label2 = TexMobject("(1-", "y",")")
minus = TexMobject("-")
nat_log = TexMobject("ln")
bra = TexMobject("(")
ket = TexMobject(")")
error_sum1.add(y_label, nat_log, bra, neuron_label[0], ket, minus)
error_sum2.add(y_label2, nat_log.copy(), bra.copy(),
TexMobject("1-"), neuron_label[1], ket.copy())
error_sum1.arrange(RIGHT, buff=SMALL_BUFF)
error_sum2.arrange(RIGHT, buff=SMALL_BUFF)
# Combine the error_sums so that we can manipulate easier
error_sum = VGroup(*[error_sum1, error_sum2])
error_sum.arrange(DOWN)
error_sum[0].align_to(error_sum[1], LEFT)
y_label[-1].set_color(YELLOW)
y_label2[-2].set_color(YELLOW)
#neuron_label.set_color(BLUE)
return error_type, error_sum, neuron_labels
def mse(self):
'''
Mean Squared Error function label
Currently not used
'''
# Define existing labels we will be copying and moving around
neuron_labels = self.neuron_labels[-1][-1].copy()
neuron_labels.generate_target()
error_sum = VGroup()
error_type = TextMobject("Mean Squared Error")
neuron_label = neuron_labels.target
neuron_label.scale(1./0.75)
half = TexMobject("\\frac{1}{2}")
y_label = TexMobject("y")
minus = TexMobject("-")
bra = TexMobject("(")
ket = TexMobject(")")
square = TexMobject(")^2")
error_sum.add(half, bra, y_label, minus, neuron_label, square)
error_sum.arrange(RIGHT, buff=SMALL_BUFF)