-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput_4_cs.Rout
1086 lines (1050 loc) · 41.6 KB
/
output_4_cs.Rout
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
R version 4.2.3 (2023-03-15) -- "Shortstop Beagle"
Copyright (C) 2023 The R Foundation for Statistical Computing
Platform: aarch64-apple-darwin20 (64-bit)
R é um software livre e vem sem GARANTIA ALGUMA.
Você pode redistribuí-lo sob certas circunstâncias.
Digite 'license()' ou 'licence()' para detalhes de distribuição.
R é um projeto colaborativo com muitos contribuidores.
Digite 'contributors()' para obter mais informações e
'citation()' para saber como citar o R ou pacotes do R em publicações.
Digite 'demo()' para demonstrações, 'help()' para o sistema on-line de ajuda,
ou 'help.start()' para abrir o sistema de ajuda em HTML no seu navegador.
Digite 'q()' para sair do R.
> ##### Oliver's MAC ####
> reticulate::use_python("/Users/oli/miniforge3/envs/r-tensorflow/bin/python3.8", required = TRUE)
> library(reticulate)
> reticulate::py_config()
python: /Users/oli/miniforge3/envs/r-tensorflow/bin/python3.8
libpython: /Users/oli/miniforge3/envs/r-tensorflow/lib/libpython3.8.dylib
pythonhome: /Users/oli/miniforge3/envs/r-tensorflow:/Users/oli/miniforge3/envs/r-tensorflow
version: 3.8.18 (default, Sep 11 2023, 08:17:16) [Clang 14.0.6 ]
numpy: /Users/oli/miniforge3/envs/r-tensorflow/lib/python3.8/site-packages/numpy
numpy_version: 1.24.3
NOTE: Python version was forced by use_python() function
>
> # Get command-line arguments - if called via sh
> args <- commandArgs(trailingOnly = TRUE)
> if (length(args) == 0) { # if not called via sh
+ args <- c(5, 'cs')
+ }
> F32 <- as.numeric(args[1])
> M32 <- args[2]
> print(paste("F32:", F32, "M32:", M32))
[1] "F32: 5 M32: cs"
>
>
> #### A mixture of discrete and continuous variables ####
> library(tensorflow)
> library(keras)
> library(mlt)
Carregando pacotes exigidos: basefun
Carregando pacotes exigidos: variables
> library(tram)
> library(MASS)
> library(tensorflow)
> library(keras)
> library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.1 ✔ readr 2.1.4
✔ forcats 1.0.0 ✔ stringr 1.5.0
✔ ggplot2 3.5.1 ✔ tibble 3.2.1
✔ lubridate 1.9.2 ✔ tidyr 1.3.0
✔ purrr 1.0.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::desc() masks variables::desc()
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
✖ dplyr::select() masks MASS::select()
✖ ggplot2::unit() masks variables::unit()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
> source('summerof24/utils_tf.R')
Attaching package: ‘grid’
The following object is masked from ‘package:variables’:
unit
>
> #### For TFP
> library(tfprobability)
> source('summerof24/utils_tfp.R')
>
> ##### Flavor of experiment ######
>
> #### Saving the current version of the script into runtime
> DIR = 'summerof24/runs/triangle_structured_continous/run_nodes25'
> if (!dir.exists(DIR)) {
+ dir.create(DIR, recursive = TRUE)
+ }
> # Copy this file to the directory DIR
> file.copy('summerof24/triangle_structured_continous.R', file.path(DIR, 'triangle_structured_continous.R'), overwrite=TRUE)
[1] TRUE
>
> num_epochs <- 500
> len_theta = 20 # Number of coefficients of the Bernstein polynomials
> hidden_features_I = c(2,25,25,2) #hidden_features_CS=hidden_features_I = c(2,25,25,2)
> hidden_features_CS = c(2,25,25,2)
>
> SEED = -1 #If seed > 0 then the seed is set
>
> if (F32 == 1){
+ FUN_NAME = 'DPGLinear'
+ f <- function(x) -0.3 * x
+ } else if (F32 == 2){
+ f = function(x) 2 * x**3 + x
+ FUN_NAME = 'DPG2x3+x'
+ } else if (F32 == 3){
+ f = function(x) 0.5*exp(x)
+ FUN_NAME = 'DPG0.5exp'
+ } else if (F32 == 4){
+ f = function(x) 0.75*atan(5*(x+0.12))
+ FUN_NAME = 'DPGatan'
+ } else if (F32 == 5){
+ f = function(x) 2*sin(3*x)+x
+ FUN_NAME = 'DPGSin'
+ } else {
+ stop("Unknown Function F32")
+ }
>
> # xs = seq(-1,1,0.1)
> # f = function(x) 2 * x**3 + 0.1*(x-.5)**5
> if (FALSE){
+ f = function(x) 0.75*atan(5*(x+0.12))
+ plot(xs, f(xs))
+ s=train$df_R$x2
+ hist(s, freq=FALSE, 100)
+ hist(f(s), freq=FALSE, 100)
+ }
>
> if (M32 == 'ls') {
+ MA = matrix(c(
+ 0, 'ls', 'ls',
+ 0, 0, 'ls',
+ 0, 0, 0), nrow = 3, ncol = 3, byrow = TRUE)
+ MODEL_NAME = 'ModelLS'
+ } else{
+ MA = matrix(c(
+ 0, 'ls', 'ls',
+ 0, 0, 'cs',
+ 0, 0, 0), nrow = 3, ncol = 3, byrow = TRUE)
+ MODEL_NAME = 'ModelCS'
+ }
>
>
> # fn = 'triangle_mixed_DGPLinear_ModelLinear.h5'
> # fn = 'triangle_mixed_DGPSin_ModelCS.h5'
>
> if (SEED < 0){
+ fn = file.path(DIR, paste0('triangle_mixed_', FUN_NAME, '_', MODEL_NAME))
+ } else{
+ fn = file.path(DIR, paste0('triangle_mixed_', FUN_NAME, '_', MODEL_NAME, '_SEED', SEED))
+ }
> print(paste0("Starting experiment ", fn))
[1] "Starting experiment summerof24/runs/triangle_structured_continous/run_nodes25/triangle_mixed_DPGSin_ModelCS"
>
> xs = seq(-1,1,0.1)
>
> plot(xs, -f(xs), sub=fn, xlab='x2', ylab='f(x2)', main='DGP influence of x2 on x3', cex.sub=0.4)
> ##### DGP ########
> dgp <- function(n_obs, doX=c(NA, NA, NA), seed=-1) {
+ if (seed > 0) {
+ set.seed(seed)
+ print(paste0("Setting Seed:", seed))
+ }
+ #n_obs = 1e5 n_obs = 10
+ #Sample X_1 from GMM with 2 components
+ if (is.na(doX[1])){
+ X_1_A = rnorm(n_obs, 0.25, 0.1)
+ X_1_B = rnorm(n_obs, 0.73, 0.05)
+ X_1 = ifelse(sample(1:2, replace = TRUE, size = n_obs) == 1, X_1_A, X_1_B)
+ } else{
+ X_1 = rep(doX[1], n_obs)
+ }
+ #hist(X_1)
+
+ # Sampling according to colr
+ if (is.na(doX[2])){
+ U2 = runif(n_obs)
+
+ x_2_dash = qlogis(U2)
+ #x_2_dash = h_0(x_2) + beta * X_1
+ X_2 = 1/0.42 * (x_2_dash - 2 * X_1)
+ X_2 = 1/5. * (x_2_dash - 0.4 * X_1) # 0.39450
+ X_2 = 1/5. * (x_2_dash - 1.2 * X_1)
+ #h2 = x_2_dash = 5 * x_2 + 2 * X_1
+ X_2 = 1/5. * (x_2_dash - 2 * X_1) #
+
+
+ } else{
+ X_2 = rep(doX[2], n_obs)
+ }
+
+ #hist(X_2)
+ #ds = seq(-5,5,0.1)
+ #plot(ds, dlogis(ds))
+ if (is.na(doX[3])){
+ U3 = runif(n_obs)
+ x_3_dash = qlogis(U3)
+ #h(x3|x1,x2) = 0.63*x3 - 0.2*x1 - f(x2)
+ #x_3_dash = h_0_3(x_3) + gamma_1 * X_1 + gamma_2 * X_2
+ #x_3_dash = 0.63 * x_3 -0.2 * X_1 + 1.3 * X_2
+ #x_3_dash = h(x3|x1,x2) = 0.63*x3 - 0.2*x1 - f(x2)
+ X_3 = (x_3_dash + 0.2 * X_1 + f(X_2))/0.63
+ } else{
+ X_3 = rep(doX[3], n_obs)
+ }
+
+
+ #hist(X_3)
+ A <- matrix(c(0, 1, 1, 0,0,1,0,0,0), nrow = 3, ncol = 3, byrow = TRUE)
+ dat.orig = data.frame(x1 = X_1, x2 = X_2, x3 = X_3)
+ dat.tf = tf$constant(as.matrix(dat.orig), dtype = 'float32')
+
+ q1 = quantile(dat.orig[,1], probs = c(0.05, 0.95))
+ q2 = quantile(dat.orig[,2], probs = c(0.05, 0.95))
+ q3 = quantile(dat.orig[,3], probs = c(0.05, 0.95))
+
+
+ return(list(
+ df_orig=dat.tf,
+ df_R = dat.orig,
+ #min = tf$reduce_min(dat.tf, axis=0L),
+ #max = tf$reduce_max(dat.tf, axis=0L),
+ min = tf$constant(c(q1[1], q2[1], q3[1]), dtype = 'float32'),
+ max = tf$constant(c(q1[2], q2[2], q3[2]), dtype = 'float32'),
+ type = c('c', 'c', 'c'),
+ A=A))
+ }
>
> train = dgp(40000, seed=ifelse(SEED > 0, SEED, -1))
> test = dgp(40000, seed=ifelse(SEED > 0, SEED + 1, -1))
> (global_min = train$min)
tf.Tensor([ 0.12195074 -0.80200094 -6.9466186 ], shape=(3), dtype=float32)
> (global_max = train$max)
tf.Tensor([0.7933437 0.41947293 5.2298746 ], shape=(3), dtype=float32)
> data_type = train$type
>
>
>
> #### Fitting Tram ######
> df = data.frame(train$df_orig$numpy())
> fit.orig = Colr(X2~X1, order=len_theta ,df)
> summary(fit.orig)
Continuous Outcome Logistic Regression
Call:
Colr(formula = X2 ~ X1, data = df, order = len_theta)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
X1 2.0247 0.0354 57.2 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Log-Likelihood:
-15542.85 (df = 22)
Likelihood-ratio Test: Chisq = 3351.844 on 1 degrees of freedom; p = < 2.2e-16
> confint(fit.orig) #Original
2.5 % 97.5 %
X1 1.955324 2.094085
> #dd = predict(fit.orig, newdata = data.frame(X1 = 0.5), type = 'density')
> #x2s = as.numeric(rownames(dd))
> #plot(x2s, dd, type = 'l', col='red')
>
> #?predict.tram
> summary(fit.orig)
Continuous Outcome Logistic Regression
Call:
Colr(formula = X2 ~ X1, data = df, order = len_theta)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
X1 2.0247 0.0354 57.2 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Log-Likelihood:
-15542.85 (df = 22)
Likelihood-ratio Test: Chisq = 3351.844 on 1 degrees of freedom; p = < 2.2e-16
> confint(fit.orig) #Original
2.5 % 97.5 %
X1 1.955324 2.094085
>
> # Fitting Tram
> fit.orig = Colr(x3 ~ x1 + x2 ,order=len_theta ,train$df_R)
> summary(fit.orig)
Continuous Outcome Logistic Regression
Call:
Colr(formula = x3 ~ x1 + x2, data = train$df_R, order = len_theta)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
x1 -0.05745 0.03553 -1.617 0.106
x2 -3.21209 0.02988 -107.487 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Log-Likelihood:
-102343.8 (df = 23)
Likelihood-ratio Test: Chisq = 14164.41 on 2 degrees of freedom; p = < 2.2e-16
> confint(fit.orig) #Original
2.5 % 97.5 %
x1 -0.1270842 0.01218971
x2 -3.2706653 -3.15352350
>
> len_theta_max = len_theta
> for (i in 1:nrow(MA)){ #Maximum number of coefficients (BS and Levels - 1 for the ordinal)
+ if (train$type[i] == 'o'){
+ len_theta_max = max(len_theta_max, nlevels(train$df_R[,i]) - 1)
+ }
+ }
> param_model = create_param_model(MA, hidden_features_I = hidden_features_I,
+ len_theta = len_theta_max,
+ hidden_features_CS = hidden_features_CS)
>
> x = tf$ones(shape = c(2L, 3L))
> param_model(1*x)
tf.Tensor(
[[[ 0. 0. -0.01728832 -0.03792364 0.0179775
0.03781744 0.07335504 0.03697458 0.0437044 0.03601922
0.07732162 -0.07801556 -0.03751907 0.10621301 0.04011018
0.02388951 -0.01992166 0.06196408 0.03319304 -0.03626622
-0.0001482 -0.02543717]
[ 0. 0.02837117 -0.0508099 -0.01246787 -0.10235834
0.02698962 -0.01731722 0.01828468 -0.06684107 0.0392414
0.04489633 -0.06748404 0.01086196 0.05125986 -0.09864193
0.03085744 -0.03078635 0.05545762 -0.03211628 0.0075481
0.04260648 0.06768831]
[-0.02270124 0.04683077 0.04674211 -0.02354205 0.00157011
-0.11736383 0.02675097 -0.03127564 0.05571634 -0.13056135
0.03415527 -0.0611145 -0.02942347 0.01793351 0.03682052
0.09655598 -0.01483436 -0.01729213 -0.02147303 -0.01692348
0.00590079 -0.03915462]]
[[ 0. 0. -0.01728832 -0.03792364 0.0179775
0.03781744 0.07335504 0.03697458 0.0437044 0.03601922
0.07732162 -0.07801556 -0.03751907 0.10621301 0.04011018
0.02388951 -0.01992166 0.06196408 0.03319304 -0.03626622
-0.0001482 -0.02543717]
[ 0. 0.02837117 -0.0508099 -0.01246787 -0.10235834
0.02698962 -0.01731722 0.01828468 -0.06684107 0.0392414
0.04489633 -0.06748404 0.01086196 0.05125986 -0.09864193
0.03085744 -0.03078635 0.05545762 -0.03211628 0.0075481
0.04260648 0.06768831]
[-0.02270124 0.04683077 0.04674211 -0.02354205 0.00157011
-0.11736383 0.02675097 -0.03127564 0.05571634 -0.13056135
0.03415527 -0.0611145 -0.02942347 0.01793351 0.03682052
0.09655598 -0.01483436 -0.01729213 -0.02147303 -0.01692348
0.00590079 -0.03915462]]], shape=(2, 3, 22), dtype=float32)
> MA
[,1] [,2] [,3]
[1,] "0" "ls" "ls"
[2,] "0" "0" "cs"
[3,] "0" "0" "0"
> h_params = param_model(train$df_orig)
> # Check the derivatives of h w.r.t. x
> x <- tf$ones(shape = c(2L, 3L)) #B,P
> with(tf$GradientTape(persistent = TRUE) %as% tape, {
+ tape$watch(x)
+ y <- param_model(x)
+ })
> # parameter (output) has shape B, P, k (num param)
> # derivation of param wrt to input x
> # input x has shape B, P
> # derivation d has shape B,P,k, B,P
> d <- tape$jacobian(y, x)
> d[1,,,2,] # only contains zero since independence of batches
tf.Tensor(
[[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]], shape=(3, 22, 3), dtype=float32)
>
>
> # loss before training
> struct_dag_loss(t_i=train$df_orig, h_params=h_params)
tf.Tensor(2.532668, shape=(), dtype=float32)
Warning message:
In force(if_any_TRUE) :
Indexing tensors are passed as-is to python, no index offsetting or R to python translation is performed. Selected options for one_based and inclusive_stop are ignored and treated as FALSE. To silence this warning, set options(tensorflow.extract.warn_tensors_passed_asis = FALSE)
>
> if (FALSE){
+ with(tf$GradientTape(persistent = TRUE) %as% tape, {
+ h_params = param_model(train$df_orig)
+ loss = struct_dag_loss(train$df_orig, h_params)
+ })
+ gradients = tape$gradient(loss, param_model$trainable_variables)
+ gradients
+ }
>
> param_model = create_param_model(MA, hidden_features_I=hidden_features_I, len_theta=len_theta, hidden_features_CS=hidden_features_CS)
>
>
> # ######### DEBUG TRAINING FROM HAND #######
> # # Define the optimizer
> # optimizer <- tf$optimizers$Adam(lr=0.01)
> # # Define the number of epochs for training
> # num_epochs <- 10
> # for (epoch in 1:num_epochs) {
> # with(tf$GradientTape(persistent = TRUE) %as% tape, {
> # # Compute the model's prediction - forward pass
> # h_params <- param_model(train$df_scaled)
> # loss <- struct_dag_loss(train$df_scaled, h_params)
> # })
> # # Compute gradients
> # gradients <- tape$gradient(loss, param_model$trainable_variables)
> # # Apply gradients to update the model parameters
> # optimizer$apply_gradients(purrr::transpose(list(gradients, param_model$trainable_variables)))
> # # Print the loss every epoch or more frequently if desired
> # print(paste("Epoch", epoch, ", Loss:", loss$numpy()))
> # }
>
>
> optimizer = optimizer_adam()
WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.Adam` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.Adam`.
> param_model$compile(optimizer, loss=struct_dag_loss)
WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.Adam`.
> param_model$evaluate(x = train$df_orig, y=train$df_orig, batch_size = 7L)
1/5715 [..............................] - ETA: 38:38 - loss: 2.5252 81/5715 [..............................] - ETA: 3s - loss: 2.5260 208/5715 [>.............................] - ETA: 2s - loss: 2.5258 340/5715 [>.............................] - ETA: 2s - loss: 2.5261 470/5715 [=>............................] - ETA: 2s - loss: 2.5261 597/5715 [==>...........................] - ETA: 2s - loss: 2.5262 725/5715 [==>...........................] - ETA: 2s - loss: 2.5261 853/5715 [===>..........................] - ETA: 2s - loss: 2.5261 980/5715 [====>.........................] - ETA: 1s - loss: 2.52611108/5715 [====>.........................] - ETA: 1s - loss: 2.52601236/5715 [=====>........................] - ETA: 1s - loss: 2.52591363/5715 [======>.......................] - ETA: 1s - loss: 2.52591491/5715 [======>.......................] - ETA: 1s - loss: 2.52601619/5715 [=======>......................] - ETA: 1s - loss: 2.52611747/5715 [========>.....................] - ETA: 1s - loss: 2.52611874/5715 [========>.....................] - ETA: 1s - loss: 2.52612003/5715 [=========>....................] - ETA: 1s - loss: 2.52602128/5715 [==========>...................] - ETA: 1s - loss: 2.52602254/5715 [==========>...................] - ETA: 1s - loss: 2.52612382/5715 [===========>..................] - ETA: 1s - loss: 2.52612510/5715 [============>.................] - ETA: 1s - loss: 2.52612636/5715 [============>.................] - ETA: 1s - loss: 2.52602764/5715 [=============>................] - ETA: 1s - loss: 2.52602891/5715 [==============>...............] - ETA: 1s - loss: 2.52613016/5715 [==============>...............] - ETA: 1s - loss: 2.52613144/5715 [===============>..............] - ETA: 1s - loss: 2.52613271/5715 [================>.............] - ETA: 0s - loss: 2.52613398/5715 [================>.............] - ETA: 0s - loss: 2.52613527/5715 [=================>............] - ETA: 0s - loss: 2.52613655/5715 [==================>...........] - ETA: 0s - loss: 2.52613782/5715 [==================>...........] - ETA: 0s - loss: 2.52613909/5715 [===================>..........] - ETA: 0s - loss: 2.52614037/5715 [====================>.........] - ETA: 0s - loss: 2.52604164/5715 [====================>.........] - ETA: 0s - loss: 2.52614289/5715 [=====================>........] - ETA: 0s - loss: 2.52614415/5715 [======================>.......] - ETA: 0s - loss: 2.52614543/5715 [======================>.......] - ETA: 0s - loss: 2.52604670/5715 [=======================>......] - ETA: 0s - loss: 2.52614798/5715 [========================>.....] - ETA: 0s - loss: 2.52614925/5715 [========================>.....] - ETA: 0s - loss: 2.52615052/5715 [=========================>....] - ETA: 0s - loss: 2.52615179/5715 [==========================>...] - ETA: 0s - loss: 2.52615306/5715 [==========================>...] - ETA: 0s - loss: 2.52615434/5715 [===========================>..] - ETA: 0s - loss: 2.52625561/5715 [============================>.] - ETA: 0s - loss: 2.52625685/5715 [============================>.] - ETA: 0s - loss: 2.52615715/5715 [==============================] - 3s 397us/step - loss: 2.5261
[1] 2.526145
>
>
> ##### Training or readin of weights if h5 available ####
> fnh5 = paste0(fn, '_E', num_epochs, '.h5')
> fnRdata = paste0(fn, '_E', num_epochs, '.RData')
> if (file.exists(fnh5)){
+ param_model$load_weights(fnh5)
+ load(fnRdata) #Loading of the workspace causes trouble e.g. param_model is zero
+ # Quick Fix since loading global_min causes problem (no tensors as RDS)
+ (global_min = train$min)
+ (global_max = train$max)
+ } else {
+ if (FALSE){ ### Full Training w/o diagnostics
+ hist = param_model$fit(x = train$df_orig, y=train$df_orig, epochs = 200L,verbose = TRUE)
+ param_model$save_weights(fn)
+ plot(hist$epoch, hist$history$loss)
+ plot(hist$epoch, hist$history$loss, ylim=c(1.07, 1.2))
+ } else { ### Training with diagnostics
+ ws <- data.frame(w12 = numeric())
+ train_loss <- numeric()
+ val_loss <- numeric()
+
+ # Training loop
+ for (e in 1:num_epochs) {
+ print(paste("Epoch", e))
+ hist <- param_model$fit(x = train$df_orig, y = train$df_orig,
+ epochs = 1L, verbose = TRUE,
+ validation_data = list(test$df_orig,test$df_orig))
+
+ # Append losses to history
+ train_loss <- c(train_loss, hist$history$loss)
+ val_loss <- c(val_loss, hist$history$val_loss)
+
+ # Extract specific weights
+ w <- param_model$get_layer(name = "beta")$get_weights()[[1]]
+
+ ws <- rbind(ws, data.frame(w12 = w[1, 2], w13 = w[1, 3], w23 = w[2, 3]))
+ }
+ # Save the model
+ param_model$save_weights(fnh5)
+ save(train_loss, val_loss, train_loss, f, MA, len_theta,
+ hidden_features_I,
+ hidden_features_CS,
+ ws,
+ #global_min, global_max,
+ file = fnRdata)
+ }
+ }
tf.Tensor([0.7933437 0.41947293 5.2298746 ], shape=(3), dtype=float32)
>
> ####### FINISHED TRAINING #####
> #pdf(paste0('loss_',fn,'.pdf'))
> epochs = length(train_loss)
> plot(1:length(train_loss), train_loss, type='l', main='Training (black: train, green: valid)')
> lines(1:length(train_loss), val_loss, type = 'l', col = 'green')
>
> # Last 50
> diff = max(epochs - 50,1)
> plot(diff:epochs, val_loss[diff:epochs], type = 'l', col = 'green', main='Last 50 epochs')
> lines(diff:epochs, train_loss[diff:epochs], type='l')
>
> # plot(1:epochs, ws[,1], type='l', main='Coef', ylim=c(-0.5, 3))#, ylim=c(0, 6))
> # abline(h=2, col='green')
> # lines(1:epochs, ws[,2], type='l', ylim=c(0, 3))
> # abline(h=0.2, col='green')
> # lines(1:epochs, ws[,3], type='l', ylim=c(0, 3))
> # abline(h=-0.3, col='green')
>
>
> ggplot(ws, aes(x=1:nrow(ws))) +
+ geom_line(aes(y=w12, color='x1 --> x2')) +
+ geom_line(aes(y=w13, color='x1 --> x3')) +
+ geom_line(aes(y=w23, color='x2 --> x3')) +
+ geom_hline(aes(yintercept=2, color='x1 --> x2'), linetype=2) +
+ geom_hline(aes(yintercept=-0.2, color='x1 --> x3'), linetype=2) +
+ geom_hline(aes(yintercept=+0.3, color='x2 --> x3'), linetype=2) +
+ #scale_color_manual(values=c('x1 --> x2'='skyblue', 'x1 --> x3='red', 'x2 --> x3'='darkgreen')) +
+ labs(x='Epoch', y='Coefficients') +
+ theme_minimal() +
+ theme(legend.title = element_blank()) # Removes the legend title
>
> if (FALSE){
+ p = ggplot(ws, aes(x=1:nrow(ws))) +
+ geom_line(aes(y=w12, color="beta12")) +
+ geom_line(aes(y=w13, color="beta13")) +
+ #geom_line(aes(y=w23, color="beta23")) +
+ geom_hline(aes(yintercept=2, color="beta12"), linetype=2) +
+ geom_hline(aes(yintercept=-0.2, color="beta13"), linetype=2) +
+ #geom_hline(aes(yintercept=+0.3, color="beta23"), linetype=2) +
+ scale_color_manual(
+ values=c('beta12'='skyblue', 'beta13'='red'),
+ labels=c(expression(beta[12]), expression(beta[13]))
+ ) +
+ labs(x='Epoch', y='Coefficients') +
+ theme_minimal() +
+ theme(
+ legend.title = element_blank(), # Removes the legend title
+ legend.position = c(0.85, 0.25), # Adjust this to position the legend inside the plot (lower-right)
+ legend.background = element_rect(fill="white", colour="black") # Optional: white background with border
+ )
+
+ file_name <- paste0(fn, "_coef_epoch.pdf")
+ # Save the plot
+ ggsave(file_name, plot = p, width = 8, height = 6)
+ file_path <- file.path("/Users/oli/Library/CloudStorage/Dropbox/Apps/Overleaf/tramdag/figures", basename(file_name))
+ ggsave(file_path, plot = p, width = 8/2, height = 6/2)
+ }
>
> if (FALSE){
+ # Creating the figure for the paper
+ # triangle_mixed_DPGLinear_ModelLS_coef_epoch
+ p = ggplot(ws, aes(x=1:nrow(ws))) +
+ geom_line(aes(y=w12, color="beta12")) +
+ geom_line(aes(y=w13, color="beta13")) +
+ geom_line(aes(y=w23, color="beta23")) +
+ geom_hline(aes(yintercept=2, color="beta12"), linetype=2) +
+ geom_hline(aes(yintercept=-0.2, color="beta13"), linetype=2) +
+ geom_hline(aes(yintercept=+0.3, color="beta23"), linetype=2) +
+ scale_color_manual(
+ values=c('beta12'='skyblue', 'beta13'='red', 'beta23'='darkgreen'),
+ labels=c(expression(beta[12]), expression(beta[13]), expression(beta[23]))
+ ) +
+ labs(x='Epoch', y='Coefficients') +
+ theme_minimal() +
+ theme(
+ legend.title = element_blank(), # Removes the legend title
+ legend.position = c(0.85, 0.25), # Adjust this to position the legend inside the plot (lower-right)
+ legend.background = element_rect(fill="white", colour="black") # Optional: white background with border
+ )
+
+ file_name <- paste0(fn, "_coef_epoch.pdf")
+ # Save the plot
+ ggsave(file_name, plot = p, width = 8, height = 6)
+ file_path <- file.path("/Users/oli/Library/CloudStorage/Dropbox/Apps/Overleaf/tramdag/figures", basename(file_name))
+ ggsave(file_path, plot = p, width = 8/2, height = 6/2)
+ }
>
> param_model$evaluate(x = train$df_orig, y=train$df_scaled) #Does not work, probably TF Eager vs Compiled
1/1250 [..............................] - ETA: 1:52 - loss: 0.0000e+00 153/1250 [==>...........................] - ETA: 0s - loss: 0.0000e+00 373/1250 [=======>......................] - ETA: 0s - loss: 0.0000e+00 594/1250 [=============>................] - ETA: 0s - loss: 0.0000e+00 815/1250 [==================>...........] - ETA: 0s - loss: 0.0000e+001035/1250 [=======================>......] - ETA: 0s - loss: 0.0000e+001250/1250 [==============================] - 0s 240us/step - loss: 0.0000e+00
[1] 0
> # One more step to estimate NLL
> if (FALSE){
+ vals = NULL
+ for (i in 1:10){
+ test = dgp(40000, i+10001)
+ hist = param_model$fit(x = train$df_orig, y = train$df_orig,
+ epochs = 1L, verbose = TRUE,
+ validation_data = list(test$df_orig,test$df_orig))
+ vals = append(vals, hist$history$val_loss)
+ }
+ t.test(vals)
+ M32
+ F32
+ }
> fn
[1] "summerof24/runs/triangle_structured_continous/run_nodes25/triangle_mixed_DPGSin_ModelCS"
> len_theta
[1] 20
> param_model$get_layer(name = "beta")$get_weights() * param_model$get_layer(name = "beta")$mask
tf.Tensor(
[[[ 0. 1.9702578 -0.20844626]
[-0. -0. 0. ]
[ 0. 0. 0. ]]], shape=(1, 3, 3), dtype=float32)
>
>
> #### Checking the transformation ####
> h_params = param_model(train$df_orig)
> r = check_baselinetrafo(h_params)
> Xs = r$Xs
> h_I = r$h_I
>
> ##### X1
> fit.1 = Colr(X1~1,df, order=len_theta)
> plot(fit.1, which = 'baseline only', main='Black: COLR, Red: Our Model')
> lines(Xs[,1], h_I[,1], col='red', lty=2, lwd=3)
> rug(train$df_orig$numpy()[,1], col='blue')
>
>
> df = data.frame(train$df_orig$numpy())
> fit.21 = Colr(X2~X1,df, order=len_theta)
> temp = model.frame(fit.21)[1:2,-1, drop=FALSE] #WTF!
> plot(fit.21, which = 'baseline only', newdata = temp, lwd=2, col='blue',
+ main='h_I(X2) Black: COLR, Red: Our Model', cex.main=0.8)
> lines(Xs[,2], h_I[,2], col='red', lty=2, lwd=5)
> rug(train$df_orig$numpy()[,2], col='blue')
>
> fit.312 = Colr(X3 ~ X1 + X2,df, order=len_theta)
> temp = model.frame(fit.312)[1:2, -1, drop=FALSE] #WTF!
>
> plot(fit.312, which = 'baseline only', newdata = temp, lwd=2, col='blue',
+ main='h_I(X3) Colr and Our Model', cex.main=0.8)
> lines(Xs[,3], h_I[,3], col='red', lty=2, lwd=5)
> rug(train$df_orig$numpy()[,3], col='blue')
>
>
> if (FALSE){
+ # Check the derivatives of h w.r.t. x
+ x <- tf$ones(shape = c(10L, 3L)) #B,P
+ with(tf$GradientTape(persistent = TRUE) %as% tape, {
+ tape$watch(x)
+ y <- param_model(x)
+ })
+ d <- tape$jacobian(y, x)
+ for (k in 1:(2+len_theta)){ #k = 1
+ print(k) #B,P,k,B,P
+ B = 1
+ print(d[B,,k,B,]) #
+ }
+ }
>
> ##### Checking observational distribution ####
> library(car)
Carregando pacotes exigidos: carData
Attaching package: ‘car’
The following object is masked from ‘package:dplyr’:
recode
The following object is masked from ‘package:purrr’:
some
> s = do_dag_struct(param_model, train$A, doX=c(NA, NA, NA), num_samples = 5000)
sample_from_target Fraction of extrapolated samples > 1 : %f
0.127599999308586sample_from_target Fraction of extrapolated samples > 1 : %f
0.130933329463005sample_from_target Fraction of extrapolated samples > 1 : %f
0.0497333332896233> par(mfrow=c(1,3))
> for (i in 1:3){
+ d = s[,i]$numpy()
+ hist(train$df_orig$numpy()[,i], freq=FALSE, 100,main=paste0("X",i, " red: ours, black: data"), xlab='samples')
+ lines(density(train$df_orig$numpy()[,i]), col='blue')
+ #hist(train$df_orig$numpy()[,i], freq=FALSE, 100,main=paste0("X_",i))
+ lines(density(s[,i]$numpy()), col='red')
+ #qqplot(train$df_orig$numpy()[,i], s[,i]$numpy())
+ #abline(0,1)
+ }
> par(mfrow=c(1,1))
>
> ######### Simulation of do-interventions #####
> doX=c(0.2, NA, NA)
> dx0.2 = dgp(10000, doX=doX, seed=SEED)
> dx0.2$df_orig$numpy()[1:5,]
[,1] [,2] [,3]
[1,] 0.2 0.4301810 0.5272594
[2,] 0.2 0.1562689 0.1659960
[3,] 0.2 -0.1948354 -3.2156334
[4,] 0.2 0.5249609 7.4184871
[5,] 0.2 -0.4459323 -3.9932337
>
>
> doX=c(0.7, NA, NA)
> dx7 = dgp(10000, doX=doX, seed=SEED)
> #hist(dx0.2$df_orig$numpy()[,2], freq=FALSE,100)
> mean(dx7$df_orig$numpy()[,2]) - mean(dx0.2$df_orig$numpy()[,2])
[1] -0.2040161
> mean(dx7$df_orig$numpy()[,3]) - mean(dx0.2$df_orig$numpy()[,3])
[1] -1.091718
>
> ########### Do(x1) seems to work#####
>
> #### Check intervention distribution after do(X1=0.2)
> df = data.frame(train$df_orig$numpy())
> fit.x2 = Colr(X2~X1,df)
> x2_dense = predict(fit.x2, newdata = data.frame(X1 = 0.2), type = 'density')
> x2s = as.numeric(rownames(x2_dense))
>
> ## samples from x2 under do(x1=0.2) via simulate
> ddd = as.numeric(unlist(simulate(fit.x2, newdata = data.frame(X1 = 0.2), nsim = 1000)))
> s2_colr = rep(NA, length(ddd))
> for (i in 1:length(ddd)){
+ s2_colr[i] = as.numeric(ddd[[i]]) #<--TODO somethimes
+ }
>
> if(sum(is.na(s2_colr)) > 0){
+ stop("Pechgehabt mit Colr, viel Glück und nochmals!")
+ }
>
> hist(dx0.2$df_orig$numpy()[,2], freq=FALSE, 100, main='Do(X1=0.2) X2',
+ sub='Histogram from DGP with do. Blue: Colr', xlab='samples')
> lines(x2s, x2_dense, type = 'l', col='blue', lw=2)
>
> # fit.x3 = Colr(X3 ~ X1 + X2,df)
> # newdata = data.frame(
> # X1 = rep(0.2, length(s2_colr)),
> # X2 = s2_colr)
> #
> # s3_colr = rep(NA, nrow(newdata))
> # for (i in 1:nrow(newdata)){
> # # i = 2
> # s3_colr[i] = simulate(fit.x3, newdata = newdata[i,], nsim = 1)
> # }
>
> s_dag = do_dag_struct(param_model, train$A, doX=c(0.2, NA, NA))
sample_from_target Fraction of extrapolated samples > 1 : %f
0.1417146474123sample_from_target Fraction of extrapolated samples > 1 : %f
0.0623800382018089> hist(dx0.2$df_orig$numpy()[,2], freq=FALSE, 50, main='X2 | Do(X1=0.2)', xlab='samples',
+ sub='Histogram from DGP with do. red:TRAM_DAG')
> sample_dag_0.2 = s_dag[,2]$numpy()
> lines(density(sample_dag_0.2), col='red', lw=2)
> m_x2_do_x10.2 = median(sample_dag_0.2)
>
>
> s_dag = do_dag_struct(param_model, train$A, doX=c(0.2, NA, NA))
sample_from_target Fraction of extrapolated samples > 1 : %f
0.137555986642838sample_from_target Fraction of extrapolated samples > 1 : %f
0.0639795288443565> hist(dx0.2$df_orig$numpy()[,3], freq=FALSE, 50, main='X3 | Do(X1=0.2)', xlab='samples',
+ sub='Histogram from DGP with do. red:TRAM_DAG')
> sample_dag_0.2 = s_dag[,3]$numpy()
> lines(density(sample_dag_0.2), col='red', lw=2)
>
>
> ###### Comparison of estimated f(x2) vs TRUE f(x2) #######
> shift_12 = shift_23 = shift1 = cs_23 = xs = seq(-1,1,length.out=41)
> idx0 = which(xs == 0) #Index of 0 xs needs to be odd
> for (i in 1:length(xs)){
+ #i = 1
+ x = xs[i]
+ # Varying x1
+ X = tf$constant(c(x, 0.5, 3), shape=c(1L,3L))
+ shift1[i] = param_model(X)[1,3,2]$numpy() #2=LS Term X1->X3
+ shift_12[i] = param_model(X)[1,2,2]$numpy() #2=LS Term X1->X2
+
+ #Varying x2
+ X = tf$constant(c(0.5, x, 3), shape=c(1L,3L))
+ cs_23[i] = param_model(X)[1,3,1]$numpy() #1=CS Term
+ shift_23[i] = param_model(X)[1,3,2]$numpy() #2-LS Term X2-->X3 (Beate Notation)
+ }
>
> if (FALSE){
+ if (MA[2,3] == 'cs' && F32 == 1){
+ # Assuming xs, cs_23, and idx0 are predefined vectors
+ # Create a data frame for the ggplot
+ df <- data.frame(x2 = xs, cs_23 = cs_23)
+
+ # Create the ggplot
+ p <- ggplot(df, aes(x = x2, y = cs_23)) +
+ geom_line(aes(color = "Complex Shift Estimate"), size = 1) +
+ geom_point(aes(color = "Complex Shift Estimate"), size = 1) +
+ geom_abline(aes(color = "f"), intercept = cs_23[idx0], slope = 0.3, size = 1) + # Black solid line for 'DGP'
+ scale_color_manual(
+ values = c("Complex Shift Estimate" = "blue", "f" = "black"), # Set colors
+ labels = c("Complex Shift Estimate", "f(x)") # Custom legend labels with expression for f(X_2)
+ ) +
+ labs(
+ x = expression(x[2]), # Subscript for x_2
+ y = "~f(x)", # Optionally leave y-axis label blank
+ color = NULL # Removes the color legend title
+ ) +
+ theme_minimal() +
+ theme(legend.position = "none") # Correct way to remove the legend
+
+ # Display the plot
+ p
+ } else if (MA[2,3] == 'cs' && F32 != 1){
+ # Assuming xs, shift_23, and idx0 are predefined vectors
+ # Create a data frame for the ggplot
+ df <- data.frame(x2 = xs,
+ shift_23 = cs_23 + ( -cs_23[idx0] - f(0)),
+ f = -f(xs)
+ )
+ # Create the ggplot
+ p <- ggplot(df, aes(x = x2, y = shift_23)) +
+ #geom_line(aes(color = "Shift Estimate"), size = 1) + # Blue line for 'Shift Estimate'
+ geom_point(aes(color = "Shift Estimate"), size = 1) + # Blue points for 'Shift Estimate'
+ geom_line(aes(color = "f", y = f), ) + # Black solid line for 'DGP'
+ scale_color_manual(
+ values = c("Shift Estimate" = "blue", "f" = "black"), # Set colors
+ labels = c("Shift Estimate", "f(x)") # Custom legend labels with expression for f(X_2)
+ ) +
+ labs(
+ x = expression(x[2]), # Subscript for x_2
+ y = "~f(x)", # Optionally leave y-axis label blank
+ color = NULL # Removes the color legend title
+ ) +
+ theme_minimal() +
+ theme(legend.position = "none") # Correct way to remove the legend
+
+ # Display the plot
+ p
+ } else{
+ print(paste0("Unknown Model ", MA[2,3]))
+ }
+
+
+ file_name <- paste0(fn, "_f23_est.pdf")
+ # Save the plot
+ ggsave(file_name, plot = p, width = 8, height = 8)
+ file_path <- file.path("/Users/oli/Library/CloudStorage/Dropbox/Apps/Overleaf/tramdag/figures", basename(file_name))
+ ggsave(file_path, plot = p, width = 8/3, height = 8/3)
+ }
>
>
> par(mfrow=c(2,2))
> plot(xs, shift_12, main='LS-Term (black DGP, red Ours)',
+ sub = 'Effect of x1 on x2',
+ xlab='x1', col='red')
> abline(0, 2)
>
> delta_0 = shift1[idx0] - 0
> plot(xs, shift1 - delta_0, main='LS-Term (black DGP, red Ours)',
+ sub = paste0('Effect of x1 on x3, delta_0 ', round(delta_0,2)),
+ xlab='x1', col='red')
> abline(0, -.2)
>
>
> if (F32 == 1){ #Linear DGP
+ if (MA[2,3] == 'ls'){
+ delta_0 = shift_23[idx0] - f(0)
+ plot(xs, shift_23 - delta_0, main='LS-Term (black DGP, red Ours)',
+ sub = paste0('Effect of x2 on x3, delta_0 ', round(delta_0,2)),
+ xlab='x2', col='red')
+ #abline(shift_23[length(shift_23)/2], -0.3)
+ abline(0, 0.3)
+ }
+ if (MA[2,3] == 'cs'){
+ plot(xs, cs_23, main='CS-Term (black DGP, red Ours)', xlab='x2',
+ sub = 'Effect of x2 on x3',col='red')
+
+ abline(cs_23[idx0], 0.3)
+ }
+ } else{ #Non-Linear DGP
+ if (MA[2,3] == 'ls'){
+ delta_0 = shift_23[idx0] + f(0)
+ plot(xs, shift_23 - delta_0, main='LS-Term (black DGP, red Ours)',
+ sub = paste0('Effect of x2 on x3, delta_0 ', round(delta_0,2)),
+ xlab='x2', col='red')
+ lines(xs, -f(xs))
+ } else if (MA[2,3] == 'cs'){
+ plot(xs, cs_23 + ( -cs_23[idx0] - f(0) ),
+ ylab='CS',
+ main='CS-Term (black DGP f2(x), red Ours)', xlab='x2',
+ sub = 'Effect of x2 on x3',col='red')
+ lines(xs, -f(xs))
+ } else{
+ print(paste0("Unknown Model ", MA[2,3]))
+ }
+ }
> #plot(xs,f(xs), xlab='x2', main='DGP')
> par(mfrow=c(1,1))
>
>
> if (TRUE){
+ ####### Compplete transformation Function #######
+ ### Copied from structured DAG Loss
+ t_i = train$df_orig
+ k_min <- k_constant(global_min)
+ k_max <- k_constant(global_max)
+
+ # from the last dimension of h_params the first entriy is h_cs1
+ # the second to |X|+1 are the LS
+ # the 2+|X|+1 to the end is H_I
+ h_cs <- h_params[,,1, drop = FALSE]
+ h_ls <- h_params[,,2, drop = FALSE]
+ #LS
+ h_LS = tf$squeeze(h_ls, axis=-1L)#tf$einsum('bx,bxx->bx', t_i, beta)
+ #CS
+ h_CS = tf$squeeze(h_cs, axis=-1L)
+
+ theta_tilde <- h_params[,,3:dim(h_params)[3], drop = FALSE]
+ theta = to_theta3(theta_tilde)
+ cont_dims = which(data_type == 'c') #1 2
+ cont_ord = which(data_type == 'o') #3
+
+ ### Continiuous dimensions
+ #### At least one continuous dimension exits
+ h_I = h_dag_extra(t_i[,cont_dims, drop=FALSE], theta[,cont_dims,1:len_theta,drop=FALSE], k_min[cont_dims], k_max[cont_dims])
+
+ h = h_I + h_LS[,cont_dims, drop=FALSE] + h_CS[,cont_dims, drop=FALSE]
+
+ ####### DGP Transformations #######
+ X_1 = t_i[,1]$numpy()
+ X_2 = t_i[,2]$numpy()
+ X_3 = t_i[,3]$numpy()
+
+ #h2 = x_2_dash = 5 * x_2 + 2 * X_1
+ h2_DGP = 5 *X_2 + 2 * X_1
+ h2_DGP_LS = 2 * X_1
+ h2_DGP_CS = rep(0, length(X_2))
+ h2_DGP_I = 5 * X_2
+
+ #h(x3|x1,x2) = 0.63*x3 - 0.2*x1 - f(x2)
+ h3_DGP = 0.63*X_3 - 0.2*X_1 - f(X_2)
+ h3_DGP_LS = -0.2*X_1
+ h3_DGP_CS = -f(X_2)
+ h3_DGP_I = 0.63*X_3
+
+
+ par(mfrow=c(2,2))
+ plot(h2_DGP, h[,2]$numpy(), main='h2')
+ abline(0,1,col='red')
+ confint(lm(h[,2]$numpy() ~ h2_DGP))
+
+ #Same for Intercept
+ plot(h2_DGP_I, h_I[,2]$numpy(), main='h2_I')
+ abline(0,1,col='red')
+ confint(lm(h_I[,2]$numpy() ~ h2_DGP_I))
+
+ plot(h2_DGP_LS, h_LS[,2]$numpy(), main='h2_LS')
+ abline(0,1,col='red')
+ confint(lm(h_LS[,2]$numpy() ~ h2_DGP_LS))
+
+ #Same for CS
+ plot(h2_DGP_CS, h_CS[,2]$numpy(), main='h2_CS')
+ abline(0,1,col='red')
+ confint(lm(h_CS[,2]$numpy() ~ h2_DGP_CS))
+
+ par(mfrow=c(1,1))
+
+
+ par(mfrow=c(2,2))