-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlearning_zero.jl
2534 lines (2075 loc) · 86 KB
/
learning_zero.jl
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
### A Pluto.jl notebook ###
# v0.19.30
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ aab65a5a-7633-11ee-22b9-0fd54ecd9118
begin
using Plots
using Lux, Optimisers
using Random
using ProgressLogging
import Flux: onehotbatch, onecold, crossentropy, throttle, softmax
using Base.Iterators: repeated, partition
using Distributions
using LinearAlgebra
using JuMP, Ipopt
using PlutoLinks, PlutoHooks
using PlutoUI
using HypertextLiteral
using Statistics
end
# ╔═╡ 730e3bd1-47af-4588-b5bd-a7c5212d7a07
md"""
# Understanding zero with deep learning
## Background
Experiments have been conducted where an animal is presented with two cards and has to choose the card with the smallest number of blobs. Once the animal understands the task, it is presented with two cards where one of the cards has zero blobs. Since the animal has not been shown a zero blob card, it has to use numerical intuition to choose which card has less blobs.
Experiments have shown that animals do have the numerical intuition to understand that zero is less than one:
* [https://science.sciencemag.org/content/334/6063/1664.abstract](https://science.sciencemag.org/content/334/6063/1664.abstract)
* [https://www.ncbi.nlm.nih.gov/pubmed/27666660](https://www.ncbi.nlm.nih.gov/pubmed/27666660)
* [https://www.researchgate.net/publication/325684091_Numerical_ordering_of_zero_in_honey_bees](https://www.researchgate.net/publication/325684091_Numerical_ordering_of_zero_in_honey_bees)
The simplest animal capable of understanding that zero is less than one is a honeybee.
## Results
In this notebook, I train a neural network to predict which of two images has less blobs. Then I give the network a scenario where one image has zero blobs. If the neural network is well trained, then it will correctly identify that zero is less than one.
## Reflections
Thinking about the training process and results broadened my perspective on what "training a neural network" means. The samples where one image has zero blobs come from a very different distribution than the training distribution. However, the model is able to make the correct prediction. Training the neural network on data gives it numerical intuition. Even though the models task is to label data, it has obtained the ability to understand numbers.
"""
# ╔═╡ f60e0e23-e304-4fa7-813d-c9be87e33f9e
TableOfContents()
# ╔═╡ c266f191-408a-4c7d-b094-69318eadb8d9
md"""
# Choose the image height and width
"""
# ╔═╡ 027a9c72-0e28-41de-88b8-68b717813383
begin
img_height = 28
img_width = 28
end
# ╔═╡ bf6f23c9-6062-4017-ad17-e1f3527881e6
md"""
# Generate examples
You can create samples of the data that the model will be trained on.
The code below uses `generate_example`, `generate_batch`, `generate_locations`, `get_title` and `plot_first_example`. Control click on the links below to see the documentation and definitions of these functions.
"""
# ╔═╡ efc39144-ea2a-4e0a-800f-8b6e72868ccf
md"""
Blobs left: $(@bind blobs_left NumberField(0:10, default=1))
Blobs right: $(@bind blobs_right NumberField(0:10, default=3))
Shape: $(@bind shape Select([:square, :gaussian]))
Scale: $(@bind scale Select([false, true]))
"""
# ╔═╡ 6b560bcb-8dc5-4386-beb8-588a73572cc1
md"""
# Use the `generate_batch` function
The `generate_batch` function randomly samples a number of blobs for the right and left images along with shapes for the blobs. For every example it creates, it will create an example where the images are flipped. Since the number of blobs left and right are generated by the function, each example can have a label attached to it. The `plot_first_example` function understands the labelling system and can create a labelled visualization of the first example in a batch.
"""
# ╔═╡ a7eebcab-29bb-4f09-84b9-cb60f23d936d
@bind go_generate_batch Button("Generate batch")
# ╔═╡ 045ac160-430a-4564-b8ed-aefbcf644b07
md"""
## Batch structure
Each batch is a 2 tuple where the first element is the data and the second is the label.
The data is a `img_height`×`img_width`× 2 ×`batch_size` array. Lux will use the last dimension as the batch dimension and each sample will be a `img_height`×`img_width` with two channels. The first channel is the left image and the second channel is the right image.
The labels are 3 × `batch_size` one hot matrices.
* first row == 1 => more blobs in the left image
* second row == 1 => same number of blobs in both images
* third row == 1 => more blobs in the right image
"""
# ╔═╡ 0898c0b2-4b2b-4b7d-bb61-27c5fba67708
md"""
Example batch size: $(@bind example_batch_size NumberField(2:2:20, default=6))
"""
# ╔═╡ 20bea86c-3c47-40d3-891d-1164aad54285
md"""
# Deep learning model (using Lux.jl)
"""
# ╔═╡ af10bdf8-1193-4fb3-8154-859025ed79e5
model = Chain(
# First convolution, operating upon a 28x28 image
Conv((3, 3), 2 => 16, pad=(1, 1), relu),
MaxPool((2, 2)),
# Second convolution, operating upon a 14x14 image
Conv((3, 3), 16 => 32, pad=(1, 1), relu),
MaxPool((2, 2)),
# Third convolution, operating upon a 7x7 image
Conv((3, 3), 32 => 32, pad=(1, 1), relu),
MaxPool((2, 2)),
# Reshape 3d tensor into a 2d one, at this point it should be (3, 3, 32, N)
# which is where we get the 288 in the `Dense` layer below:
x -> reshape(x, :, size(x, 4)),
Dropout(0.2),
Dense(288, 3, relu),
# Softmax to get probabilities
softmax,
)
# ╔═╡ c2c9439d-9adb-40b3-8482-2911a182e898
md"""
## Crossentropy loss
"""
# ╔═╡ 3f8bdd08-dccb-4a79-ba28-27bf0a209385
function loss(model, ps, st, data)
y_pred, st = Lux.apply(model, data[1], ps, st)
ce_loss = crossentropy(y_pred, data[2])
return ce_loss, st, ()
end
# ╔═╡ 6d2d0dde-cb24-41d0-a7e5-3dd3e462d6b0
function accuracy(tstate, data)
ŷ = onecold(Lux.apply(tstate.model, data[1], tstate.parameters, tstate.states)[1],
[-1 0 1])
mean(ŷ .== onecold(data[2], [-1, 0, 1]))
end
# ╔═╡ 7cef11de-5616-4d4e-b760-2aa1da00be5b
md"""
## Training loop
"""
# ╔═╡ fda7447b-7915-4027-ae28-592476124b42
function train_model(model, opt, train_data, test_data, nepoch)
rng = MersenneTwister(42)
tstate = Lux.Training.TrainState(rng, model, opt)
vjp_rule = Lux.Training.AutoZygote()
test_accuracy_list = Float64[]
batch_loss_list = Float32[]
for epoch in 1:nepoch
for batch in train_data
grads, loss_value, stats, tstate = Lux.Training.compute_gradients(
vjp_rule,
loss,
batch,
tstate
)
tstate = Lux.Training.apply_gradients(tstate, grads)
end
test_accuracy = accuracy(tstate, test_data)
train_loss = mean(
loss(tstate.model, tstate.parameters, tstate.states, batch)[1]
for batch in train_data
)
@info "
Epcoh: $epoch
Test accuracy: $(test_accuracy)
Train loss: $train_loss"
push!(test_accuracy_list, test_accuracy)
push!(batch_loss_list, train_loss)
end
tstate, test_accuracy_list, batch_loss_list
end
# ╔═╡ f88e7b88-8730-4d9f-bee6-4594d045135e
md"""
## Generate train/test data
"""
# ╔═╡ 9a959062-2eea-4d3b-a4be-4f99c6668deb
md"""
## Select training parameters
"""
# ╔═╡ a6918b7b-1f91-43dc-8826-59cefa3ad706
opt = Optimisers.Adam(1f-3)
# ╔═╡ cf23ff89-bf31-4b41-ad2e-d82b149df17f
rng = MersenneTwister()
# ╔═╡ 015ad06d-0b40-421d-88f0-0b4204faa7d8
md"""
# Evaluate model
The figure below shows the accuracy of the model given the number of blobs in the left/right images. Since there are three classes and the classes are balanced in the training set, random guessing would give you an accuracy of 1/3, which the model exceeds.
The first column and the last row of the heatmap below are cases where the model was presented with a image with zero blobs. The fact that the model does better than 1/3 in these cases indicates that it understands zero.
"""
# ╔═╡ 5b1fad09-ae8b-4a10-b985-6fb054c2fc78
md"""
## Make predictions with the model
Pressing the button below will generate a sample from the training distribution and predict which side has more blobs. The prediction is compared to the true label and the status of the model prediction is shown.
"""
# ╔═╡ a03d9cf7-7812-449a-a2ea-f76d15e0ce7b
@bind go Button("Generate a sample from the training distribution and compare to model prediction")
# ╔═╡ 553ce5e1-6d21-4cc5-a624-664c2d365035
md"""
## Choose your own adventure
Use the input fields to choose the characteristics of the input data and see how the model performs.
"""
# ╔═╡ e682454f-54fd-4faf-8268-869914f1ec8f
md"""
Blobs left: $(@bind blobs_left_ NumberField(0:10, default=0))
Blobs right: $(@bind blobs_right_ NumberField(0:10, default=3))
Shape: $(@bind shape_ Select([:square, :gaussian]))
Scale: $(@bind scale_ Select([false, true]))
$(@bind go_ Button("Generate another example"))
"""
# ╔═╡ 250fd052-a5fb-4c17-b6b9-dea0b53f6243
md"""
# Appendix (helper functions)
"""
# ╔═╡ 706be74a-e527-418d-8a2f-532af2fe27d5
"""
generate_locations(nobjects; min_distance=1.0)
Randomly generate coordinates for `nobjects` lying in the square [-1,1]×[-1,1]. Each
point has to be atleast `min_distance` from all other points.
# Implementation
`generate_locations` will sample `nobjects` points in the square using a uniform
distribution. Then it will find locations that are as close as possible to the sampled
locations while maintaining the distance constraint. JuMP and Ipopt are used to set up
and solve the optimization problem.
"""
function generate_locations(nobjects; min_distance=1.0)
object_locations = 2rand(2, nobjects) .- 1
model = Model(Ipopt.Optimizer)
set_attribute(model, "print_level", 0)
@variable(model, -1.0 <= x[1:nobjects] <= 1.0)
@variable(model, -1.0 <= y[1:nobjects] <= 1.0)
pairs = [(i, j) for i in 1:nobjects, j in 1:nobjects if j != i]
pi = [p[1] for p in pairs]
pj = [p[2] for p in pairs]
@constraint(model,
(x[pi] .- x[pj]).^2 .+
(y[pi] .- y[pj]).^2 .>= min_distance^2)
@objective(model, Min,
sum((x[i] - object_locations[1, i])^2
+ (y[i] - object_locations[2, i])^2
for i in 1:nobjects))
optimize!(model)
permutedims([value.(x) value.(y)])
end
# ╔═╡ 288ce71f-4e53-4fab-ae70-32bd7e325da3
function add_blobs!(img, xx, yy, shape, object_locations, object_size, scale)
nobjects = size(object_locations, 2)
for index in 1:nobjects
l_x, l_y = object_locations[:, index]
if shape == :square
scaling = scale ? min(nobjects, 4) : 1.0
img .+= [ifelse((abs(x - l_x) < object_size/scaling)
&& (abs(y - l_y) < object_size/scaling), 1.0, 0.0)
for x in xx, y in yy]
elseif shape == :gaussian
scaling = scale ? object_size*sqrt(nobjects) : object_size
img .+= [exp(-scaling*((x - l_x)^2 + (y - l_y)^2))
for x in xx, y in yy]
end
end
img
end
# ╔═╡ efc93fb2-255e-4ef7-8606-1936c7a5f370
"""
generate_example(img_height, img_width, nobjects::Tuple;
μ=50, σ=0.5,
min_distance=0.7,
noise_strength=0.02,
shape=:gaussian,
scale=false))
Generate an example image of height `img_height` and width `img_width` containing
`nobjects[1]` objects on the left side and `nobjects[2]` objects on the right side.
The shape of the object is determined by the `shape` keyword argument.
"""
function generate_example(img_height, img_width, nobjects::Tuple;
μ=50, σ=0.5,
min_distance=0.7,
noise_strength=0.02,
shape=:gaussian,
scale=false)
object_locations1 = generate_locations(abs(nobjects[1]); min_distance)
object_locations2 = generate_locations(abs(nobjects[2]); min_distance)
object_size = shape == :square ? 0.25 : 50.0
img1 = randn(img_height, img_width)*noise_strength
img2 = randn(img_height, img_width)*noise_strength
xx = LinRange(-1, 1, img_width)
yy = LinRange(-1, 1, img_height)
add_blobs!(img1, xx, yy, shape, object_locations1, object_size, scale)
add_blobs!(img2, xx, yy, shape, object_locations2, object_size, scale)
ret = Array{Float32}(undef, size(img1)..., 2)
ret[:, :, 1] .= img1
ret[:, :, 2] .= img2
ret
end
# ╔═╡ 1b56681e-c486-498e-bc34-040698b025b7
begin
example = generate_example(img_height, img_width, (blobs_left, blobs_right),
shape=shape, scale=scale)
img = hcat(example[:, :, 1], ones(img_height, 1)*NaN, example[:, :, 2])
heatmap(img, ratio=1)
end
# ╔═╡ 39c4bfff-5c1e-4d40-bceb-cfcee66805f8
heatmap(img, ratio=1)
# ╔═╡ cc5ad985-945d-4186-9ec8-7ce3f6c3ea1c
function test_i_j(state, model, i, j; img_height=img_height, img_width=img_width)
img = reshape(
generate_example(img_height, img_width,
(i, j);
scale=rand([true, false]),
shape=rand([:square, :gaussian, :circle])
),
(img_height, img_width, 2, 1)
)
model_result = Lux.apply(model, img, state.parameters, state.states)[1]
label = onecold(model_result, [-1 0 1])[1]
label == sign(j - i)
end
# ╔═╡ cab297cb-ee7a-4413-a545-4c1293ef72d8
"""
generate_batch(batch_size, img_height, img_width)
Generate `batch_size` examples with images of size `img_height`×`img_width` along
with their (onehot encoded) labels.
"""
function generate_batch(batch_size, img_height, img_width)
nobjects_range = 1:5
labels = Array{Int}(undef, batch_size)
data = Array{Float32}(undef, img_height, img_width, 2, batch_size)
for i in 1:2:batch_size
nobjects = rand(nobjects_range, 2)
# Rebalance the training set so that there is approximately the same number
# of examples with equal as blobs as unequal blob examples.
rand() <= 0.2 && (nobjects[1] = nobjects[2])
labels[i] = nobjects[1] > nobjects[2] ? -1 :
nobjects[1] == nobjects[2] ? 0 : 1
data[:, :, :, i] .= generate_example(img_height, img_width,
(nobjects[1], nobjects[2]);
scale=rand([true, false]),
shape=rand([:square, :gaussian])
)
# Generate another example where the images flip sides.
labels[i + 1] = nobjects[2] > nobjects[1] ? -1 :
nobjects[1] == nobjects[2] ? 0 : 1
data[:, :, :, i + 1] .= reverse(data[:, :, :, i], dims=3)
end
data, onehotbatch(labels, [-1 0 1])
end
# ╔═╡ f56ea23e-8af6-4777-b717-e1d13cd91c8a
begin
example_batch = generate_batch(example_batch_size, img_width, img_height)
nothing
end
# ╔═╡ 8a3125f0-90d8-426f-876f-07e28492d1bf
example_batch[1]
# ╔═╡ 7c165cbd-b21b-4150-ad2e-9aedd5629f48
example_batch[2]
# ╔═╡ 06975abb-a62b-42a3-bf9f-199d52f33453
begin
batch_size = 64
nbatch_train = 15
ntest = 200
train_data = [generate_batch(batch_size, img_height, img_width)
for _ in 1:nbatch_train]
test_data = generate_batch(ntest, img_height, img_width)
end
# ╔═╡ 0622c381-faba-4c60-a556-78d0c90cbc64
begin
nepoch = 60
trained_state, test_accuracy, batch_loss_list =
train_model(model, opt, train_data, test_data, nepoch)
end
# ╔═╡ 0c90e26c-e00d-44b1-b692-cde77c294302
let
p1 = plot(test_accuracy,
xlabel="Epoch",
ylabel="Test accuracy",
legend=false
)
p2 = plot(batch_loss_list,
xlabel="Epoch",
ylabel="Training loss",
legend=false
)
plot(p1, p2, layout=(2, 1))
end
# ╔═╡ 2eff527d-897d-4606-874f-7b5e645e4c23
begin
test_range = 0:5
niters = 20
accuracy_matrix = [mean(test_i_j(trained_state, model, i, j) for _ in 1:niters)
for i in test_range, j in test_range]
p1 = heatmap(test_range, test_range, accuracy_matrix, colorbar_title="Accuracy")
xaxis!("# blobs left")
yaxis!("# blobs right")
end
# ╔═╡ 12b07d79-f13a-42a9-8dc4-12422d760a7e
function get_title(label)
if label == 1
"Right has more blobs"
elseif label == 0
"Same number of blobs"
else
"Left has more blobs"
end
end
# ╔═╡ a240ddb8-7b7e-4cb9-a58b-837ea7232afb
let
go_
sample = generate_example(img_height, img_width,
(blobs_left_, blobs_right_),
shape=shape_, scale=scale_)
img = hcat(sample[:, :, 1], ones(img_height, 1)*NaN, sample[:, :, 2])
prediction = Lux.apply(trained_state.model,
reshape(sample, (img_height, img_width, 2, 1)),
trained_state.parameters, trained_state.states)[1]
model_label = onecold(prediction, [-1 0 1])[1]
p = heatmap(img, ratio=1)
data_label = sign(blobs_right_ - blobs_left_)
is_correct = model_label == data_label
text_color = is_correct ? "green" : "red"
@htl("""
$(p)
<br>
<b style="color:$(text_color);font-size:2.1em">
Model $(is_correct ? "correctly" : "incorrectly") predicts "$(get_title(model_label) |> lowercase)"
</b>
""")
end
# ╔═╡ 07ca44b6-d8b8-463b-8374-e28af9a50738
function plot_first_example(batch; show_all=true)
data = batch[1]
img1 = hcat(data[:, :, 1, 1], ones(img_height)*NaN, data[:, :, 2, 1])
img2 = hcat(data[:, :, 1, 2], ones(img_height)*NaN, data[:, :, 2, 2])
label = onecold(batch[2], [-1 0 1])[1]
title = get_title(label)
p1 = heatmap(img1; title)
label = onecold(batch[2], [-1 0 1])[2]
title = get_title(label)
p2 = heatmap(img2; title)
if show_all
plot(p1, p2, layout=(2, 1))
else
p1
end
end
# ╔═╡ 5fbeb830-4265-44fc-a2f0-814dfc6728e0
generate_example, generate_batch, generate_locations, get_title, plot_first_example
# ╔═╡ bcb32bfe-1bd5-4c89-b08f-527f23906bc9
let
go_generate_batch
batch = generate_batch(2, img_width, img_height)
plot_first_example(batch)
end
# ╔═╡ 01e8c15b-ada6-4747-920f-47a11117248a
let
go
batch = generate_batch(2, img_width, img_height)
p = plot_first_example(batch; show_all=false)
prediction = Lux.apply(trained_state.model, batch[1],
trained_state.parameters, trained_state.states)[1]
model_label = onecold(prediction, [-1 0 1])[1]
data_label = onecold(batch[2], [-1 0 1])[1]
is_correct = model_label == data_label
text_color = is_correct ? "green" : "red"
@htl("""
$(p)
<b style="color:$(text_color);font-size:2.1em">
Model $(is_correct ? "correctly" : "incorrectly") predicts "$(get_title(model_label) |> lowercase)"
</b>
""")
end
# ╔═╡ 6f51041b-74f9-4beb-aab8-670ec38ca425
plot()
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
Flux = "587475ba-b771-5e3f-ad9e-33799f191a9c"
HypertextLiteral = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
Ipopt = "b6b21f68-93f8-5de0-b562-5493be1d77c9"
JuMP = "4076af6c-e467-56ae-b986-b466b2749572"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Lux = "b2108857-7c20-44ae-9111-449ecde12c47"
Optimisers = "3bd65402-5787-11e9-1adc-39752487f4e2"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoHooks = "0ff47ea0-7a50-410d-8455-4348d5de0774"
PlutoLinks = "0ff47ea0-7a50-410d-8455-4348d5de0420"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
ProgressLogging = "33c8b6b6-d38a-422a-b730-caa89a2f386c"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[compat]
Distributions = "~0.25.102"
Flux = "~0.14.6"
HypertextLiteral = "~0.9.4"
Ipopt = "~1.5.1"
JuMP = "~1.16.0"
Lux = "~0.5.9"
Optimisers = "~0.3.1"
Plots = "~1.39.0"
PlutoHooks = "~0.0.5"
PlutoLinks = "~0.1.6"
PlutoUI = "~0.7.52"
ProgressLogging = "~0.1.4"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.9.2"
manifest_format = "2.0"
project_hash = "d5e3df9f75e4d7c97c37ff583d6749d72c98bf34"
[[deps.ADTypes]]
git-tree-sha1 = "5d2e21d7b0d8c22f67483ef95ebdc39c0e6b6003"
uuid = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
version = "0.2.4"
[[deps.ASL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6252039f98492252f9e47c312c8ffda0e3b9e78d"
uuid = "ae81ac8f-d209-56e5-92de-9978fef736f9"
version = "0.1.3+0"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "91bd53c39b9cbfb5ef4b015e8b582d344532bd0a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.2.0"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "02f731463748db57cc2ebfbd9fbc9ce8280d3433"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.7.1"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.ArgCheck]]
git-tree-sha1 = "a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4"
uuid = "dce04be8-c92d-5529-be00-80e4d2c0e197"
version = "2.3.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Atomix]]
deps = ["UnsafeAtomics"]
git-tree-sha1 = "c06a868224ecba914baa6942988e2f2aade419be"
uuid = "a9b6321e-bd34-4604-b9c9-b65b8de01458"
version = "0.1.0"
[[deps.BangBang]]
deps = ["Compat", "ConstructionBase", "InitialValues", "LinearAlgebra", "Requires", "Setfield", "Tables"]
git-tree-sha1 = "e28912ce94077686443433c2800104b061a827ed"
uuid = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"
version = "0.3.39"
[deps.BangBang.extensions]
BangBangChainRulesCoreExt = "ChainRulesCore"
BangBangDataFramesExt = "DataFrames"
BangBangStaticArraysExt = "StaticArrays"
BangBangStructArraysExt = "StructArrays"
BangBangTypedTablesExt = "TypedTables"
[deps.BangBang.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
TypedTables = "9d95f2ec-7b3d-5a63-8d20-e2491e220bb9"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.Baselet]]
git-tree-sha1 = "aebf55e6d7795e02ca500a689d326ac979aaf89e"
uuid = "9718e550-a3fa-408a-8086-8db961cd8217"
version = "0.1.1"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "d9a9701b899b30332bbcb3e1679c41cce81fb0e8"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.3.2"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.CEnum]]
git-tree-sha1 = "eb4cb44a499229b3b8426dcfb5dd85333951ff90"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.2"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.1"
[[deps.ChainRules]]
deps = ["Adapt", "ChainRulesCore", "Compat", "Distributed", "GPUArraysCore", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "SparseInverseSubset", "Statistics", "StructArrays", "SuiteSparse"]
git-tree-sha1 = "7e4f5593e7e1ab923cebc5414f6d5433872cdd19"
uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2"
version = "1.56.0"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra"]
git-tree-sha1 = "e0af648f0692ec1691b5d094b8724ba1346281cf"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.18.0"
weakdeps = ["SparseArrays"]
[deps.ChainRulesCore.extensions]
ChainRulesCoreSparseArraysExt = "SparseArrays"
[[deps.CodeTracking]]
deps = ["InteractiveUtils", "UUIDs"]
git-tree-sha1 = "c0216e792f518b39b22212127d4a84dc31e4e386"
uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2"
version = "1.3.5"
[[deps.CodecBzip2]]
deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"]
git-tree-sha1 = "c0ae2a86b162fb5d7acc65269b469ff5b8a73594"
uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd"
version = "0.8.1"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "cd67fc487743b2f0fd4380d4cbd3a24660d0eec8"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.3"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "67c1f244b991cad9b0aa4b7540fb758c2488b129"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.24.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"]
git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.10.0"
weakdeps = ["SpecialFunctions"]
[deps.ColorVectorSpace.extensions]
SpecialFunctionsExt = "SpecialFunctions"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "8a62af3e248a8c4bad6b32cbbe663ae02275e32c"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.10.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.5+0"
[[deps.CompositionsBase]]
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.2"
[deps.CompositionsBase.extensions]
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
[deps.CompositionsBase.weakdeps]
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.ConcreteStructs]]
git-tree-sha1 = "f749037478283d372048690eb3b5f92a79432b34"
uuid = "2569d6c7-a4a2-43d3-a901-331e8e4be471"
version = "0.2.3"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "5372dbbf8f0bdb8c700db5367132925c0771ef7e"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.2.1"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "c53fc348ca4d40d7b371e71fd52251839080cbc9"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.4"
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseStaticArraysExt = "StaticArrays"
[deps.ConstructionBase.weakdeps]
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.ContextVariablesX]]
deps = ["Compat", "Logging", "UUIDs"]
git-tree-sha1 = "25cc3803f1030ab855e383129dcd3dc294e322cc"
uuid = "6add18c4-b38d-439d-96f6-d6bc489c04c5"
version = "0.1.3"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.DataAPI]]
git-tree-sha1 = "8da84edb865b0b5b0100c0666a9bc9a0b71c553c"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.15.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "3dbd312d370723b6bb43ba9d02fc36abade4518d"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.15"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DefineSingletons]]
git-tree-sha1 = "0fba8b706d0178b4dc7fd44a96a92382c9065c2c"
uuid = "244e2a9f-e319-4986-a169-4d1fe445cd52"
version = "0.1.2"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "23163d55f885173722d1e4cf0f6110cdbaf7e272"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.15.1"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Distributions]]
deps = ["FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns", "Test"]
git-tree-sha1 = "3d5873f811f582873bb9871fc9c451784d5dc8c7"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.102"
[deps.Distributions.extensions]
DistributionsChainRulesCoreExt = "ChainRulesCore"
DistributionsDensityInterfaceExt = "DensityInterface"
[deps.Distributions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DensityInterface = "b429d917-457f-4dbc-8f4c-0cc954292b1d"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.DualNumbers]]
deps = ["Calculus", "NaNMath", "SpecialFunctions"]
git-tree-sha1 = "5837a837389fccf076445fce071c8ddaea35a566"
uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74"
version = "0.6.8"
[[deps.EpollShim_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8e9441ee83492030ace98f9789a654a6d0b1f643"
uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43"
version = "0.0.20230411+0"
[[deps.ExceptionUnwrapping]]
deps = ["Test"]
git-tree-sha1 = "e90caa41f5a86296e014e148ee061bd6c3edec96"
uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4"
version = "0.1.9"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "4558ab818dcceaab612d1bb8c19cee87eda2b83c"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.5.0+0"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Pkg", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "74faea50c1d007c85837327f6775bea60b5492dd"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.2+2"
[[deps.FLoops]]
deps = ["BangBang", "Compat", "FLoopsBase", "InitialValues", "JuliaVariables", "MLStyle", "Serialization", "Setfield", "Transducers"]
git-tree-sha1 = "ffb97765602e3cbe59a0589d237bf07f245a8576"
uuid = "cc61a311-1640-44b5-9fba-1b764f453329"
version = "0.2.1"
[[deps.FLoopsBase]]
deps = ["ContextVariablesX"]
git-tree-sha1 = "656f7a6859be8673bf1f35da5670246b923964f7"
uuid = "b9860ae5-e623-471e-878b-f6a53c775ea6"
version = "0.1.1"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random"]
git-tree-sha1 = "35f0c0f345bff2c6d636f95fdb136323b5a796ef"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "1.7.0"
weakdeps = ["SparseArrays", "Statistics"]