Resume SynthData0523 main/c6 batch 16
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +22 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_mlp.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_simple.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/importance.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacies.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacy.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_catboost.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_mlp.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/importance.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_catboost.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_mlp.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_simple.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacies.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacy.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.py +12 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/__init__.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/data.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/deep.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/env.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/metrics.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/util.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.py +719 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.py +168 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.py +39 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.py +158 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.py +433 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txt +22 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.sh +5 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.sh +5 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.py +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/__init__.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_catboost.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_mlp.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_simple.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/sample.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/train.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/utils_train.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.py +145 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.py +176 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.py +121 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.py +130 -0
.gitattributes
CHANGED
|
@@ -5249,3 +5249,25 @@ SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wi
|
|
| 5249 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ctabgan/privacies.json filter=lfs diff=lfs merge=lfs -text
|
| 5250 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 5251 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5249 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ctabgan/privacies.json filter=lfs diff=lfs merge=lfs -text
|
| 5250 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 5251 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5252 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_mlp.json filter=lfs diff=lfs merge=lfs -text
|
| 5253 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 5254 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/importance.json filter=lfs diff=lfs merge=lfs -text
|
| 5255 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/info.json filter=lfs diff=lfs merge=lfs -text
|
| 5256 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacies.json filter=lfs diff=lfs merge=lfs -text
|
| 5257 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacy.json filter=lfs diff=lfs merge=lfs -text
|
| 5258 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 5259 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5260 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_mlp.json filter=lfs diff=lfs merge=lfs -text
|
| 5261 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/importance.json filter=lfs diff=lfs merge=lfs -text
|
| 5262 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/info.json filter=lfs diff=lfs merge=lfs -text
|
| 5263 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 5264 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5265 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_mlp.json filter=lfs diff=lfs merge=lfs -text
|
| 5266 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 5267 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/info.json filter=lfs diff=lfs merge=lfs -text
|
| 5268 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacies.json filter=lfs diff=lfs merge=lfs -text
|
| 5269 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacy.json filter=lfs diff=lfs merge=lfs -text
|
| 5270 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 5271 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5272 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 5273 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json filter=lfs diff=lfs merge=lfs -text
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_mlp.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2df86c0b6c8fc0e216a53438e3f26bd9e46670c1f5b3dc77426259c971d210f3
|
| 3 |
+
size 1319
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/eval_simple.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2f8ca0f43e784616f459b84a576d98839d9abe41af934709640dc8e81efb4e98
|
| 3 |
+
size 6621
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/importance.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04f31ef7049dee20af09577fe45fb41d805af0907e8e137ee3516d0e90d2554f
|
| 3 |
+
size 301
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:511a0dc9860b7587f2382407ae286e4160a320f28a3b2bff6bd85ce88a6550e4
|
| 3 |
+
size 191
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacies.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f42ff2e01094cd2102a388e7fd6124eb7b7cbf899b465cacf0860127e4c99e78
|
| 3 |
+
size 223
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_cb_best/privacy.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c87fcede2165d9a1cc54de5f114c0cfdaa21c0dc8a1dbe6ed1232e8e930df025
|
| 3 |
+
size 40
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:636b5d5b2495c4c123f00fead30911369c615118fbffa66f12610fcfc4c730ba
|
| 3 |
+
size 936
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_catboost.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:722b3ac7a315c79a1bc37fe46cec8ac815bef9599406c0734cb78c095698f0f8
|
| 3 |
+
size 1318
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/eval_mlp.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8e04b6d0b94b457eacd407d0338fa99146f6749339d4b64b48001287daa5b7b5
|
| 3 |
+
size 664
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/importance.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9cc24aa23a4db246ab5dfe17125252a50009917323d54e5677507aba6b7f0a38
|
| 3 |
+
size 298
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/ddpm_mlp_best/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:511a0dc9860b7587f2382407ae286e4160a320f28a3b2bff6bd85ce88a6550e4
|
| 3 |
+
size 191
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e161c1def56ea993fc1e643c986456388df3cabfae0c4213cb15565a17e0dcd2
|
| 3 |
+
size 400
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_catboost.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4712ec1d5d364761ad171d82d98b083e0e8b567649793dfa488478beef453c08
|
| 3 |
+
size 664
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_mlp.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9063998cac822118a02b7b2d2a568d909c04fc994db129345a81a481a4fd0956
|
| 3 |
+
size 1315
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/eval_simple.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:61fe10a9440af4534e2826cbc566e5192f7ae8947c598d2e84fe619b37a359ac
|
| 3 |
+
size 3319
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:511a0dc9860b7587f2382407ae286e4160a320f28a3b2bff6bd85ce88a6550e4
|
| 3 |
+
size 191
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacies.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5b6a5e9214b8d7e50524a5e9177419661add5dc4d3b06ecffe68c7cb4c5f392
|
| 3 |
+
size 223
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/smote/privacy.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4aa03c0df6c8ca6742c1489e8e37ac08f68c342c863bddf7ca3143426920c576
|
| 3 |
+
size 40
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:50edc7be21196e9e790fe8990bc332150d0550db1b2c46e60d19810e875a3ece
|
| 3 |
+
size 605
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:36cf4c644fe1879a25693cfb68d88db11c3afb7a9c075e3f4d2d1ea201ca67c5
|
| 3 |
+
size 664
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b55d374b6630709cb9d4c5814d856dd2520386b992937a3b24d80d71eb2e035c
|
| 3 |
+
size 3307
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:511a0dc9860b7587f2382407ae286e4160a320f28a3b2bff6bd85ce88a6550e4
|
| 3 |
+
size 191
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from icecream import install
|
| 3 |
+
|
| 4 |
+
torch.set_num_threads(1)
|
| 5 |
+
install()
|
| 6 |
+
|
| 7 |
+
from . import env # noqa
|
| 8 |
+
from .data import * # noqa
|
| 9 |
+
from .deep import * # noqa
|
| 10 |
+
from .env import * # noqa
|
| 11 |
+
from .metrics import * # noqa
|
| 12 |
+
from .util import * # noqa
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (573 Bytes). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/data.cpython-311.pyc
ADDED
|
Binary file (47.8 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/deep.cpython-311.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/env.cpython-311.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/metrics.cpython-311.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/util.cpython-311.pyc
ADDED
|
Binary file (27.9 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.py
ADDED
|
@@ -0,0 +1,719 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from dataclasses import astuple, dataclass, replace
|
| 5 |
+
from importlib.resources import path
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from sklearn.model_selection import train_test_split
|
| 12 |
+
from sklearn.pipeline import make_pipeline
|
| 13 |
+
import sklearn.preprocessing
|
| 14 |
+
import torch
|
| 15 |
+
import os
|
| 16 |
+
from category_encoders import LeaveOneOutEncoder
|
| 17 |
+
from sklearn.impute import SimpleImputer
|
| 18 |
+
from sklearn.preprocessing import StandardScaler
|
| 19 |
+
from scipy.spatial.distance import cdist
|
| 20 |
+
|
| 21 |
+
from . import env, util
|
| 22 |
+
from .metrics import calculate_metrics as calculate_metrics_
|
| 23 |
+
from .util import TaskType, load_json
|
| 24 |
+
|
| 25 |
+
ArrayDict = Dict[str, np.ndarray]
|
| 26 |
+
TensorDict = Dict[str, torch.Tensor]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
CAT_MISSING_VALUE = '__nan__'
|
| 30 |
+
CAT_RARE_VALUE = '__rare__'
|
| 31 |
+
Normalization = Literal['standard', 'quantile', 'minmax']
|
| 32 |
+
NumNanPolicy = Literal['drop-rows', 'mean']
|
| 33 |
+
CatNanPolicy = Literal['most_frequent']
|
| 34 |
+
CatEncoding = Literal['one-hot', 'counter']
|
| 35 |
+
YPolicy = Literal['default']
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class StandardScaler1d(StandardScaler):
|
| 39 |
+
def partial_fit(self, X, *args, **kwargs):
|
| 40 |
+
assert X.ndim == 1
|
| 41 |
+
return super().partial_fit(X[:, None], *args, **kwargs)
|
| 42 |
+
|
| 43 |
+
def transform(self, X, *args, **kwargs):
|
| 44 |
+
assert X.ndim == 1
|
| 45 |
+
return super().transform(X[:, None], *args, **kwargs).squeeze(1)
|
| 46 |
+
|
| 47 |
+
def inverse_transform(self, X, *args, **kwargs):
|
| 48 |
+
assert X.ndim == 1
|
| 49 |
+
return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]:
|
| 53 |
+
"""Return K[i] s.t. F.one_hot(x[:,i], K[i]) is valid. Requires K[i] > max(x[:,i])."""
|
| 54 |
+
XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist()
|
| 55 |
+
return [int(np.max(x)) + 1 if len(x) > 0 else 0 for x in XT]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=False)
|
| 59 |
+
class Dataset:
|
| 60 |
+
X_num: Optional[ArrayDict]
|
| 61 |
+
X_cat: Optional[ArrayDict]
|
| 62 |
+
y: ArrayDict
|
| 63 |
+
y_info: Dict[str, Any]
|
| 64 |
+
task_type: TaskType
|
| 65 |
+
n_classes: Optional[int]
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset':
|
| 69 |
+
dir_ = Path(dir_)
|
| 70 |
+
splits = [k for k in ['train', 'val', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
|
| 71 |
+
|
| 72 |
+
def load(item) -> ArrayDict:
|
| 73 |
+
return {
|
| 74 |
+
x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code]
|
| 75 |
+
for x in splits
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
if Path(dir_ / 'info.json').exists():
|
| 79 |
+
info = util.load_json(dir_ / 'info.json')
|
| 80 |
+
else:
|
| 81 |
+
info = None
|
| 82 |
+
return Dataset(
|
| 83 |
+
load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None,
|
| 84 |
+
load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None,
|
| 85 |
+
load('y'),
|
| 86 |
+
{},
|
| 87 |
+
TaskType(info['task_type']),
|
| 88 |
+
info.get('n_classes'),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def is_binclass(self) -> bool:
|
| 93 |
+
return self.task_type == TaskType.BINCLASS
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def is_multiclass(self) -> bool:
|
| 97 |
+
return self.task_type == TaskType.MULTICLASS
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def is_regression(self) -> bool:
|
| 101 |
+
return self.task_type == TaskType.REGRESSION
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def n_num_features(self) -> int:
|
| 105 |
+
return 0 if self.X_num is None else self.X_num['train'].shape[1]
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def n_cat_features(self) -> int:
|
| 109 |
+
return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def n_features(self) -> int:
|
| 113 |
+
return self.n_num_features + self.n_cat_features
|
| 114 |
+
|
| 115 |
+
def size(self, part: Optional[str]) -> int:
|
| 116 |
+
return sum(map(len, self.y.values())) if part is None else len(self.y[part])
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def nn_output_dim(self) -> int:
|
| 120 |
+
if self.is_multiclass:
|
| 121 |
+
assert self.n_classes is not None
|
| 122 |
+
return self.n_classes
|
| 123 |
+
else:
|
| 124 |
+
return 1
|
| 125 |
+
|
| 126 |
+
def get_category_sizes(self, part: str) -> List[int]:
|
| 127 |
+
return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
|
| 128 |
+
|
| 129 |
+
def calculate_metrics(
|
| 130 |
+
self,
|
| 131 |
+
predictions: Dict[str, np.ndarray],
|
| 132 |
+
prediction_type: Optional[str],
|
| 133 |
+
) -> Dict[str, Any]:
|
| 134 |
+
metrics = {
|
| 135 |
+
x: calculate_metrics_(
|
| 136 |
+
self.y[x], predictions[x], self.task_type, prediction_type, self.y_info
|
| 137 |
+
)
|
| 138 |
+
for x in predictions
|
| 139 |
+
}
|
| 140 |
+
if self.task_type == TaskType.REGRESSION:
|
| 141 |
+
score_key = 'rmse'
|
| 142 |
+
score_sign = -1
|
| 143 |
+
else:
|
| 144 |
+
score_key = 'accuracy'
|
| 145 |
+
score_sign = 1
|
| 146 |
+
for part_metrics in metrics.values():
|
| 147 |
+
part_metrics['score'] = score_sign * part_metrics[score_key]
|
| 148 |
+
return metrics
|
| 149 |
+
|
| 150 |
+
def change_val(dataset: Dataset, val_size: float = 0.2):
|
| 151 |
+
# should be done before transformations
|
| 152 |
+
|
| 153 |
+
y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
|
| 154 |
+
|
| 155 |
+
ixs = np.arange(y.shape[0])
|
| 156 |
+
if dataset.is_regression:
|
| 157 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
|
| 158 |
+
else:
|
| 159 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
|
| 160 |
+
|
| 161 |
+
dataset.y['train'] = y[train_ixs]
|
| 162 |
+
dataset.y['val'] = y[val_ixs]
|
| 163 |
+
|
| 164 |
+
if dataset.X_num is not None:
|
| 165 |
+
X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0)
|
| 166 |
+
dataset.X_num['train'] = X_num[train_ixs]
|
| 167 |
+
dataset.X_num['val'] = X_num[val_ixs]
|
| 168 |
+
|
| 169 |
+
if dataset.X_cat is not None:
|
| 170 |
+
X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0)
|
| 171 |
+
dataset.X_cat['train'] = X_cat[train_ixs]
|
| 172 |
+
dataset.X_cat['val'] = X_cat[val_ixs]
|
| 173 |
+
|
| 174 |
+
return dataset
|
| 175 |
+
|
| 176 |
+
def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset:
|
| 177 |
+
assert dataset.X_num is not None
|
| 178 |
+
nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()}
|
| 179 |
+
if not any(x.any() for x in nan_masks.values()): # type: ignore[code]
|
| 180 |
+
assert policy is None
|
| 181 |
+
return dataset
|
| 182 |
+
|
| 183 |
+
assert policy is not None
|
| 184 |
+
if policy == 'drop-rows':
|
| 185 |
+
valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()}
|
| 186 |
+
assert valid_masks[
|
| 187 |
+
'test'
|
| 188 |
+
].all(), 'Cannot drop test rows, since this will affect the final metrics.'
|
| 189 |
+
new_data = {}
|
| 190 |
+
for data_name in ['X_num', 'X_cat', 'y']:
|
| 191 |
+
data_dict = getattr(dataset, data_name)
|
| 192 |
+
if data_dict is not None:
|
| 193 |
+
new_data[data_name] = {
|
| 194 |
+
k: v[valid_masks[k]] for k, v in data_dict.items()
|
| 195 |
+
}
|
| 196 |
+
dataset = replace(dataset, **new_data)
|
| 197 |
+
elif policy == 'mean':
|
| 198 |
+
new_values = np.nanmean(dataset.X_num['train'], axis=0)
|
| 199 |
+
X_num = deepcopy(dataset.X_num)
|
| 200 |
+
for k, v in X_num.items():
|
| 201 |
+
num_nan_indices = np.where(nan_masks[k])
|
| 202 |
+
v[num_nan_indices] = np.take(new_values, num_nan_indices[1])
|
| 203 |
+
dataset = replace(dataset, X_num=X_num)
|
| 204 |
+
else:
|
| 205 |
+
assert util.raise_unknown('policy', policy)
|
| 206 |
+
return dataset
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20
|
| 210 |
+
def normalize(
|
| 211 |
+
X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False
|
| 212 |
+
) -> ArrayDict:
|
| 213 |
+
X_train = X['train']
|
| 214 |
+
if normalization == 'standard':
|
| 215 |
+
normalizer = sklearn.preprocessing.StandardScaler()
|
| 216 |
+
elif normalization == 'minmax':
|
| 217 |
+
normalizer = sklearn.preprocessing.MinMaxScaler()
|
| 218 |
+
elif normalization == 'quantile':
|
| 219 |
+
normalizer = sklearn.preprocessing.QuantileTransformer(
|
| 220 |
+
output_distribution='normal',
|
| 221 |
+
n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10),
|
| 222 |
+
subsample=int(1e9),
|
| 223 |
+
random_state=seed,
|
| 224 |
+
)
|
| 225 |
+
# noise = 1e-3
|
| 226 |
+
# if noise > 0:
|
| 227 |
+
# assert seed is not None
|
| 228 |
+
# stds = np.std(X_train, axis=0, keepdims=True)
|
| 229 |
+
# noise_std = noise / np.maximum(stds, noise) # type: ignore[code]
|
| 230 |
+
# X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal(
|
| 231 |
+
# X_train.shape
|
| 232 |
+
# )
|
| 233 |
+
else:
|
| 234 |
+
util.raise_unknown('normalization', normalization)
|
| 235 |
+
normalizer.fit(X_train)
|
| 236 |
+
if return_normalizer:
|
| 237 |
+
return {k: normalizer.transform(v) for k, v in X.items()}, normalizer
|
| 238 |
+
return {k: normalizer.transform(v) for k, v in X.items()}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict:
|
| 242 |
+
assert X is not None
|
| 243 |
+
nan_masks = {k: np.asarray(v == CAT_MISSING_VALUE) for k, v in X.items()}
|
| 244 |
+
if any(np.asarray(x).any() for x in nan_masks.values()): # type: ignore[code]
|
| 245 |
+
if policy is None:
|
| 246 |
+
X_new = X
|
| 247 |
+
elif policy == 'most_frequent':
|
| 248 |
+
imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code]
|
| 249 |
+
imputer.fit(X['train'])
|
| 250 |
+
X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()}
|
| 251 |
+
else:
|
| 252 |
+
util.raise_unknown('categorical NaN policy', policy)
|
| 253 |
+
else:
|
| 254 |
+
assert policy is None
|
| 255 |
+
X_new = X
|
| 256 |
+
return X_new
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict:
|
| 260 |
+
assert 0.0 < min_frequency < 1.0
|
| 261 |
+
min_count = round(len(X['train']) * min_frequency)
|
| 262 |
+
X_new = {x: [] for x in X}
|
| 263 |
+
for column_idx in range(X['train'].shape[1]):
|
| 264 |
+
counter = Counter(X['train'][:, column_idx].tolist())
|
| 265 |
+
popular_categories = {k for k, v in counter.items() if v >= min_count}
|
| 266 |
+
for part in X_new:
|
| 267 |
+
X_new[part].append(
|
| 268 |
+
[
|
| 269 |
+
(x if x in popular_categories else CAT_RARE_VALUE)
|
| 270 |
+
for x in X[part][:, column_idx].tolist()
|
| 271 |
+
]
|
| 272 |
+
)
|
| 273 |
+
return {k: np.array(v).T for k, v in X_new.items()}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def cat_encode(
|
| 277 |
+
X: ArrayDict,
|
| 278 |
+
encoding: Optional[CatEncoding],
|
| 279 |
+
y_train: Optional[np.ndarray],
|
| 280 |
+
seed: Optional[int],
|
| 281 |
+
return_encoder : bool = False
|
| 282 |
+
) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical)
|
| 283 |
+
if encoding != 'counter':
|
| 284 |
+
y_train = None
|
| 285 |
+
|
| 286 |
+
# Step 1. Map strings to 0-based ranges
|
| 287 |
+
|
| 288 |
+
if encoding is None:
|
| 289 |
+
unknown_value = np.iinfo('int64').max - 3
|
| 290 |
+
oe = sklearn.preprocessing.OrdinalEncoder(
|
| 291 |
+
handle_unknown='use_encoded_value', # type: ignore[code]
|
| 292 |
+
unknown_value=unknown_value, # type: ignore[code]
|
| 293 |
+
dtype='int64', # type: ignore[code]
|
| 294 |
+
).fit(X['train'])
|
| 295 |
+
encoder = make_pipeline(oe)
|
| 296 |
+
encoder.fit(X['train'])
|
| 297 |
+
X = {k: encoder.transform(v) for k, v in X.items()}
|
| 298 |
+
max_values = X['train'].max(axis=0)
|
| 299 |
+
for part in X.keys():
|
| 300 |
+
if part == 'train': continue
|
| 301 |
+
for column_idx in range(X[part].shape[1]):
|
| 302 |
+
X[part][X[part][:, column_idx] == unknown_value, column_idx] = (
|
| 303 |
+
max_values[column_idx] + 1
|
| 304 |
+
)
|
| 305 |
+
if return_encoder:
|
| 306 |
+
return (X, False, encoder)
|
| 307 |
+
return (X, False)
|
| 308 |
+
|
| 309 |
+
# Step 2. Encode.
|
| 310 |
+
|
| 311 |
+
elif encoding == 'one-hot':
|
| 312 |
+
ohe = sklearn.preprocessing.OneHotEncoder(
|
| 313 |
+
handle_unknown='ignore', sparse=False, dtype=np.float32 # type: ignore[code]
|
| 314 |
+
)
|
| 315 |
+
encoder = make_pipeline(ohe)
|
| 316 |
+
|
| 317 |
+
# encoder.steps.append(('ohe', ohe))
|
| 318 |
+
encoder.fit(X['train'])
|
| 319 |
+
X = {k: encoder.transform(v) for k, v in X.items()}
|
| 320 |
+
elif encoding == 'counter':
|
| 321 |
+
assert y_train is not None
|
| 322 |
+
assert seed is not None
|
| 323 |
+
loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False)
|
| 324 |
+
encoder.steps.append(('loe', loe))
|
| 325 |
+
encoder.fit(X['train'], y_train)
|
| 326 |
+
X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code]
|
| 327 |
+
if not isinstance(X['train'], pd.DataFrame):
|
| 328 |
+
X = {k: v.values for k, v in X.items()} # type: ignore[code]
|
| 329 |
+
else:
|
| 330 |
+
util.raise_unknown('encoding', encoding)
|
| 331 |
+
|
| 332 |
+
if return_encoder:
|
| 333 |
+
return X, True, encoder # type: ignore[code]
|
| 334 |
+
return (X, True)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def build_target(
|
| 338 |
+
y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType
|
| 339 |
+
) -> Tuple[ArrayDict, Dict[str, Any]]:
|
| 340 |
+
info: Dict[str, Any] = {'policy': policy}
|
| 341 |
+
if policy is None:
|
| 342 |
+
pass
|
| 343 |
+
elif policy == 'default':
|
| 344 |
+
if task_type == TaskType.REGRESSION:
|
| 345 |
+
mean, std = float(y['train'].mean()), float(y['train'].std())
|
| 346 |
+
y = {k: (v - mean) / std for k, v in y.items()}
|
| 347 |
+
info['mean'] = mean
|
| 348 |
+
info['std'] = std
|
| 349 |
+
else:
|
| 350 |
+
util.raise_unknown('policy', policy)
|
| 351 |
+
return y, info
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@dataclass(frozen=True)
|
| 355 |
+
class Transformations:
|
| 356 |
+
seed: int = 0
|
| 357 |
+
normalization: Optional[Normalization] = None
|
| 358 |
+
num_nan_policy: Optional[NumNanPolicy] = None
|
| 359 |
+
cat_nan_policy: Optional[CatNanPolicy] = None
|
| 360 |
+
cat_min_frequency: Optional[float] = None
|
| 361 |
+
cat_encoding: Optional[CatEncoding] = None
|
| 362 |
+
y_policy: Optional[YPolicy] = 'default'
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def transform_dataset(
|
| 366 |
+
dataset: Dataset,
|
| 367 |
+
transformations: Transformations,
|
| 368 |
+
cache_dir: Optional[Path],
|
| 369 |
+
return_transforms: bool = False
|
| 370 |
+
) -> Dataset:
|
| 371 |
+
# WARNING: the order of transformations matters. Moreover, the current
|
| 372 |
+
# implementation is not ideal in that sense.
|
| 373 |
+
if cache_dir is not None:
|
| 374 |
+
transformations_md5 = hashlib.md5(
|
| 375 |
+
str(transformations).encode('utf-8')
|
| 376 |
+
).hexdigest()
|
| 377 |
+
transformations_str = '__'.join(map(str, astuple(transformations)))
|
| 378 |
+
cache_path = (
|
| 379 |
+
cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle'
|
| 380 |
+
)
|
| 381 |
+
if cache_path.exists():
|
| 382 |
+
cache_transformations, value = util.load_pickle(cache_path)
|
| 383 |
+
if transformations == cache_transformations:
|
| 384 |
+
print(
|
| 385 |
+
f"Using cached features: {cache_dir.name + '/' + cache_path.name}"
|
| 386 |
+
)
|
| 387 |
+
return value
|
| 388 |
+
else:
|
| 389 |
+
raise RuntimeError(f'Hash collision for {cache_path}')
|
| 390 |
+
else:
|
| 391 |
+
cache_path = None
|
| 392 |
+
|
| 393 |
+
if dataset.X_num is not None:
|
| 394 |
+
dataset = num_process_nans(dataset, transformations.num_nan_policy)
|
| 395 |
+
|
| 396 |
+
num_transform = None
|
| 397 |
+
cat_transform = None
|
| 398 |
+
X_num = dataset.X_num
|
| 399 |
+
|
| 400 |
+
if X_num is not None and transformations.normalization is not None:
|
| 401 |
+
X_num, num_transform = normalize(
|
| 402 |
+
X_num,
|
| 403 |
+
transformations.normalization,
|
| 404 |
+
transformations.seed,
|
| 405 |
+
return_normalizer=True
|
| 406 |
+
)
|
| 407 |
+
num_transform = num_transform
|
| 408 |
+
|
| 409 |
+
if dataset.X_cat is None:
|
| 410 |
+
assert transformations.cat_nan_policy is None
|
| 411 |
+
assert transformations.cat_min_frequency is None
|
| 412 |
+
# assert transformations.cat_encoding is None
|
| 413 |
+
X_cat = None
|
| 414 |
+
else:
|
| 415 |
+
X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy)
|
| 416 |
+
if transformations.cat_min_frequency is not None:
|
| 417 |
+
X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency)
|
| 418 |
+
X_cat, is_num, cat_transform = cat_encode(
|
| 419 |
+
X_cat,
|
| 420 |
+
transformations.cat_encoding,
|
| 421 |
+
dataset.y['train'],
|
| 422 |
+
transformations.seed,
|
| 423 |
+
return_encoder=True
|
| 424 |
+
)
|
| 425 |
+
if is_num:
|
| 426 |
+
X_num = (
|
| 427 |
+
X_cat
|
| 428 |
+
if X_num is None
|
| 429 |
+
else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num}
|
| 430 |
+
)
|
| 431 |
+
X_cat = None
|
| 432 |
+
|
| 433 |
+
y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
|
| 434 |
+
|
| 435 |
+
dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info)
|
| 436 |
+
dataset.num_transform = num_transform
|
| 437 |
+
dataset.cat_transform = cat_transform
|
| 438 |
+
|
| 439 |
+
if cache_path is not None:
|
| 440 |
+
util.dump_pickle((transformations, dataset), cache_path)
|
| 441 |
+
# if return_transforms:
|
| 442 |
+
# return dataset, num_transform, cat_transform
|
| 443 |
+
return dataset
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def build_dataset(
|
| 447 |
+
path: Union[str, Path],
|
| 448 |
+
transformations: Transformations,
|
| 449 |
+
cache: bool
|
| 450 |
+
) -> Dataset:
|
| 451 |
+
path = Path(path)
|
| 452 |
+
dataset = Dataset.from_dir(path)
|
| 453 |
+
return transform_dataset(dataset, transformations, path if cache else None)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def prepare_tensors(
|
| 457 |
+
dataset: Dataset, device: Union[str, torch.device]
|
| 458 |
+
) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]:
|
| 459 |
+
X_num, X_cat, Y = (
|
| 460 |
+
None if x is None else {k: torch.as_tensor(v) for k, v in x.items()}
|
| 461 |
+
for x in [dataset.X_num, dataset.X_cat, dataset.y]
|
| 462 |
+
)
|
| 463 |
+
if device.type != 'cpu':
|
| 464 |
+
X_num, X_cat, Y = (
|
| 465 |
+
None if x is None else {k: v.to(device) for k, v in x.items()}
|
| 466 |
+
for x in [X_num, X_cat, Y]
|
| 467 |
+
)
|
| 468 |
+
assert X_num is not None
|
| 469 |
+
assert Y is not None
|
| 470 |
+
if not dataset.is_multiclass:
|
| 471 |
+
Y = {k: v.float() for k, v in Y.items()}
|
| 472 |
+
return X_num, X_cat, Y
|
| 473 |
+
|
| 474 |
+
###############
|
| 475 |
+
## DataLoader##
|
| 476 |
+
###############
|
| 477 |
+
|
| 478 |
+
class TabDataset(torch.utils.data.Dataset):
|
| 479 |
+
def __init__(
|
| 480 |
+
self, dataset : Dataset, split : Literal['train', 'val', 'test']
|
| 481 |
+
):
|
| 482 |
+
super().__init__()
|
| 483 |
+
|
| 484 |
+
self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None
|
| 485 |
+
self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None
|
| 486 |
+
self.y = torch.from_numpy(dataset.y[split])
|
| 487 |
+
|
| 488 |
+
assert self.y is not None
|
| 489 |
+
assert self.X_num is not None or self.X_cat is not None
|
| 490 |
+
|
| 491 |
+
def __len__(self):
|
| 492 |
+
return len(self.y)
|
| 493 |
+
|
| 494 |
+
def __getitem__(self, idx):
|
| 495 |
+
out_dict = {
|
| 496 |
+
'y': self.y[idx].long() if self.y is not None else None,
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
x = np.empty((0,))
|
| 500 |
+
if self.X_num is not None:
|
| 501 |
+
x = self.X_num[idx]
|
| 502 |
+
if self.X_cat is not None:
|
| 503 |
+
x = torch.cat([x, self.X_cat[idx]], dim=0)
|
| 504 |
+
return x.float(), out_dict
|
| 505 |
+
|
| 506 |
+
def prepare_dataloader(
|
| 507 |
+
dataset : Dataset,
|
| 508 |
+
split : str,
|
| 509 |
+
batch_size: int,
|
| 510 |
+
):
|
| 511 |
+
|
| 512 |
+
torch_dataset = TabDataset(dataset, split)
|
| 513 |
+
loader = torch.utils.data.DataLoader(
|
| 514 |
+
torch_dataset,
|
| 515 |
+
batch_size=batch_size,
|
| 516 |
+
shuffle=(split == 'train'),
|
| 517 |
+
num_workers=1,
|
| 518 |
+
)
|
| 519 |
+
while True:
|
| 520 |
+
yield from loader
|
| 521 |
+
|
| 522 |
+
def prepare_torch_dataloader(
|
| 523 |
+
dataset : Dataset,
|
| 524 |
+
split : str,
|
| 525 |
+
shuffle : bool,
|
| 526 |
+
batch_size: int,
|
| 527 |
+
) -> torch.utils.data.DataLoader:
|
| 528 |
+
|
| 529 |
+
torch_dataset = TabDataset(dataset, split)
|
| 530 |
+
loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)
|
| 531 |
+
|
| 532 |
+
return loader
|
| 533 |
+
|
| 534 |
+
def dataset_from_csv(paths : Dict[str, str], cat_features, target, T):
|
| 535 |
+
assert 'train' in paths
|
| 536 |
+
y = {}
|
| 537 |
+
X_num = {}
|
| 538 |
+
X_cat = {} if len(cat_features) else None
|
| 539 |
+
for split in paths.keys():
|
| 540 |
+
df = pd.read_csv(paths[split])
|
| 541 |
+
y[split] = df[target].to_numpy().astype(float)
|
| 542 |
+
if X_cat is not None:
|
| 543 |
+
X_cat[split] = df[cat_features].to_numpy().astype(str)
|
| 544 |
+
X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
|
| 545 |
+
|
| 546 |
+
dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train'])))
|
| 547 |
+
return transform_dataset(dataset, T, None)
|
| 548 |
+
|
| 549 |
+
class FastTensorDataLoader:
|
| 550 |
+
"""
|
| 551 |
+
A DataLoader-like object for a set of tensors that can be much faster than
|
| 552 |
+
TensorDataset + DataLoader because dataloader grabs individual indices of
|
| 553 |
+
the dataset and calls cat (slow).
|
| 554 |
+
Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6
|
| 555 |
+
"""
|
| 556 |
+
def __init__(self, *tensors, batch_size=32, shuffle=False):
|
| 557 |
+
"""
|
| 558 |
+
Initialize a FastTensorDataLoader.
|
| 559 |
+
:param *tensors: tensors to store. Must have the same length @ dim 0.
|
| 560 |
+
:param batch_size: batch size to load.
|
| 561 |
+
:param shuffle: if True, shuffle the data *in-place* whenever an
|
| 562 |
+
iterator is created out of this object.
|
| 563 |
+
:returns: A FastTensorDataLoader.
|
| 564 |
+
"""
|
| 565 |
+
assert all(t.shape[0] == tensors[0].shape[0] for t in tensors)
|
| 566 |
+
self.tensors = tensors
|
| 567 |
+
|
| 568 |
+
self.dataset_len = self.tensors[0].shape[0]
|
| 569 |
+
self.batch_size = batch_size
|
| 570 |
+
self.shuffle = shuffle
|
| 571 |
+
|
| 572 |
+
# Calculate # batches
|
| 573 |
+
n_batches, remainder = divmod(self.dataset_len, self.batch_size)
|
| 574 |
+
if remainder > 0:
|
| 575 |
+
n_batches += 1
|
| 576 |
+
self.n_batches = n_batches
|
| 577 |
+
def __iter__(self):
|
| 578 |
+
if self.shuffle:
|
| 579 |
+
r = torch.randperm(self.dataset_len)
|
| 580 |
+
self.tensors = [t[r] for t in self.tensors]
|
| 581 |
+
self.i = 0
|
| 582 |
+
return self
|
| 583 |
+
|
| 584 |
+
def __next__(self):
|
| 585 |
+
if self.i >= self.dataset_len:
|
| 586 |
+
raise StopIteration
|
| 587 |
+
batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors)
|
| 588 |
+
self.i += self.batch_size
|
| 589 |
+
return batch
|
| 590 |
+
|
| 591 |
+
def __len__(self):
|
| 592 |
+
return self.n_batches
|
| 593 |
+
|
| 594 |
+
def prepare_fast_dataloader(
|
| 595 |
+
D : Dataset,
|
| 596 |
+
split : str,
|
| 597 |
+
batch_size: int
|
| 598 |
+
):
|
| 599 |
+
if D.X_cat is not None:
|
| 600 |
+
if D.X_num is not None:
|
| 601 |
+
X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
|
| 602 |
+
else:
|
| 603 |
+
X = torch.from_numpy(D.X_cat[split]).float()
|
| 604 |
+
else:
|
| 605 |
+
X = torch.from_numpy(D.X_num[split]).float()
|
| 606 |
+
y = torch.from_numpy(D.y[split])
|
| 607 |
+
dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
|
| 608 |
+
while True:
|
| 609 |
+
yield from dataloader
|
| 610 |
+
|
| 611 |
+
def prepare_fast_torch_dataloader(
|
| 612 |
+
D : Dataset,
|
| 613 |
+
split : str,
|
| 614 |
+
batch_size: int
|
| 615 |
+
):
|
| 616 |
+
if D.X_cat is not None:
|
| 617 |
+
X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
|
| 618 |
+
else:
|
| 619 |
+
X = torch.from_numpy(D.X_num[split]).float()
|
| 620 |
+
y = torch.from_numpy(D.y[split])
|
| 621 |
+
dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
|
| 622 |
+
return dataloader
|
| 623 |
+
|
| 624 |
+
def round_columns(X_real, X_synth, columns):
|
| 625 |
+
for col in columns:
|
| 626 |
+
uniq = np.unique(X_real[:,col])
|
| 627 |
+
dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float))
|
| 628 |
+
X_synth[:, col] = uniq[dist.argmin(axis=1)]
|
| 629 |
+
return X_synth
|
| 630 |
+
|
| 631 |
+
def concat_features(D : Dataset):
|
| 632 |
+
if D.X_num is None:
|
| 633 |
+
assert D.X_cat is not None
|
| 634 |
+
X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()}
|
| 635 |
+
elif D.X_cat is None:
|
| 636 |
+
assert D.X_num is not None
|
| 637 |
+
X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()}
|
| 638 |
+
else:
|
| 639 |
+
X = {
|
| 640 |
+
part: pd.concat(
|
| 641 |
+
[
|
| 642 |
+
pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)),
|
| 643 |
+
pd.DataFrame(
|
| 644 |
+
D.X_cat[part],
|
| 645 |
+
columns=range(D.n_num_features, D.n_features),
|
| 646 |
+
),
|
| 647 |
+
],
|
| 648 |
+
axis=1,
|
| 649 |
+
)
|
| 650 |
+
for part in D.y.keys()
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
return X
|
| 654 |
+
|
| 655 |
+
def concat_to_pd(X_num, X_cat, y):
|
| 656 |
+
if X_num is None:
|
| 657 |
+
return pd.concat([
|
| 658 |
+
pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))),
|
| 659 |
+
pd.DataFrame(y, columns=['y'])
|
| 660 |
+
], axis=1)
|
| 661 |
+
if X_cat is not None:
|
| 662 |
+
return pd.concat([
|
| 663 |
+
pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
|
| 664 |
+
pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))),
|
| 665 |
+
pd.DataFrame(y, columns=['y'])
|
| 666 |
+
], axis=1)
|
| 667 |
+
return pd.concat([
|
| 668 |
+
pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
|
| 669 |
+
pd.DataFrame(y, columns=['y'])
|
| 670 |
+
], axis=1)
|
| 671 |
+
|
| 672 |
+
def read_pure_data(path, split='train'):
|
| 673 |
+
y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True)
|
| 674 |
+
X_num = None
|
| 675 |
+
X_cat = None
|
| 676 |
+
if os.path.exists(os.path.join(path, f'X_num_{split}.npy')):
|
| 677 |
+
X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True)
|
| 678 |
+
if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')):
|
| 679 |
+
X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
|
| 680 |
+
|
| 681 |
+
return X_num, X_cat, y
|
| 682 |
+
|
| 683 |
+
def read_changed_val(path, val_size=0.2):
|
| 684 |
+
path = Path(path)
|
| 685 |
+
X_num_train, X_cat_train, y_train = read_pure_data(path, 'train')
|
| 686 |
+
X_num_val, X_cat_val, y_val = read_pure_data(path, 'val')
|
| 687 |
+
is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
|
| 688 |
+
|
| 689 |
+
y = np.concatenate([y_train, y_val], axis=0)
|
| 690 |
+
|
| 691 |
+
ixs = np.arange(y.shape[0])
|
| 692 |
+
if is_regression:
|
| 693 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
|
| 694 |
+
else:
|
| 695 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
|
| 696 |
+
y_train = y[train_ixs]
|
| 697 |
+
y_val = y[val_ixs]
|
| 698 |
+
|
| 699 |
+
if X_num_train is not None:
|
| 700 |
+
X_num = np.concatenate([X_num_train, X_num_val], axis=0)
|
| 701 |
+
X_num_train = X_num[train_ixs]
|
| 702 |
+
X_num_val = X_num[val_ixs]
|
| 703 |
+
|
| 704 |
+
if X_cat_train is not None:
|
| 705 |
+
X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0)
|
| 706 |
+
X_cat_train = X_cat[train_ixs]
|
| 707 |
+
X_cat_val = X_cat[val_ixs]
|
| 708 |
+
|
| 709 |
+
return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
|
| 710 |
+
|
| 711 |
+
#############
|
| 712 |
+
|
| 713 |
+
def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]:
|
| 714 |
+
path = Path("data/" + dataset_dir_name)
|
| 715 |
+
info = util.load_json(path / 'info.json')
|
| 716 |
+
info['size'] = info['train_size'] + info['val_size'] + info['test_size']
|
| 717 |
+
info['n_features'] = info['n_num_features'] + info['n_cat_features']
|
| 718 |
+
info['path'] = path
|
| 719 |
+
return info
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import statistics
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Any, Callable, Literal, cast
|
| 4 |
+
|
| 5 |
+
import rtdl
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torch.optim as optim
|
| 10 |
+
import zero
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
|
| 13 |
+
from .util import TaskType
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def cos_sin(x: Tensor) -> Tensor:
|
| 17 |
+
return torch.cat([torch.cos(x), torch.sin(x)], -1)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class PeriodicOptions:
|
| 22 |
+
n: int # the output size is 2 * n
|
| 23 |
+
sigma: float
|
| 24 |
+
trainable: bool
|
| 25 |
+
initialization: Literal['log-linear', 'normal']
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Periodic(nn.Module):
|
| 29 |
+
def __init__(self, n_features: int, options: PeriodicOptions) -> None:
|
| 30 |
+
super().__init__()
|
| 31 |
+
if options.initialization == 'log-linear':
|
| 32 |
+
coefficients = options.sigma ** (torch.arange(options.n) / options.n)
|
| 33 |
+
coefficients = coefficients[None].repeat(n_features, 1)
|
| 34 |
+
else:
|
| 35 |
+
assert options.initialization == 'normal'
|
| 36 |
+
coefficients = torch.normal(0.0, options.sigma, (n_features, options.n))
|
| 37 |
+
if options.trainable:
|
| 38 |
+
self.coefficients = nn.Parameter(coefficients) # type: ignore[code]
|
| 39 |
+
else:
|
| 40 |
+
self.register_buffer('coefficients', coefficients)
|
| 41 |
+
|
| 42 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 43 |
+
assert x.ndim == 2
|
| 44 |
+
return cos_sin(2 * torch.pi * self.coefficients[None] * x[..., None])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_n_parameters(m: nn.Module):
|
| 48 |
+
return sum(x.numel() for x in m.parameters() if x.requires_grad)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_loss_fn(task_type: TaskType) -> Callable[..., Tensor]:
|
| 52 |
+
return (
|
| 53 |
+
F.binary_cross_entropy_with_logits
|
| 54 |
+
if task_type == TaskType.BINCLASS
|
| 55 |
+
else F.cross_entropy
|
| 56 |
+
if task_type == TaskType.MULTICLASS
|
| 57 |
+
else F.mse_loss
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def default_zero_weight_decay_condition(module_name, module, parameter_name, parameter):
|
| 62 |
+
del module_name, parameter
|
| 63 |
+
return parameter_name.endswith('bias') or isinstance(
|
| 64 |
+
module,
|
| 65 |
+
(
|
| 66 |
+
nn.BatchNorm1d,
|
| 67 |
+
nn.LayerNorm,
|
| 68 |
+
nn.InstanceNorm1d,
|
| 69 |
+
rtdl.CLSToken,
|
| 70 |
+
rtdl.NumericalFeatureTokenizer,
|
| 71 |
+
rtdl.CategoricalFeatureTokenizer,
|
| 72 |
+
Periodic,
|
| 73 |
+
),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def split_parameters_by_weight_decay(
|
| 78 |
+
model: nn.Module, zero_weight_decay_condition=default_zero_weight_decay_condition
|
| 79 |
+
) -> list[dict[str, Any]]:
|
| 80 |
+
parameters_info = {}
|
| 81 |
+
for module_name, module in model.named_modules():
|
| 82 |
+
for parameter_name, parameter in module.named_parameters():
|
| 83 |
+
full_parameter_name = (
|
| 84 |
+
f'{module_name}.{parameter_name}' if module_name else parameter_name
|
| 85 |
+
)
|
| 86 |
+
parameters_info.setdefault(full_parameter_name, ([], parameter))[0].append(
|
| 87 |
+
zero_weight_decay_condition(
|
| 88 |
+
module_name, module, parameter_name, parameter
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
params_with_wd = {'params': []}
|
| 92 |
+
params_without_wd = {'params': [], 'weight_decay': 0.0}
|
| 93 |
+
for full_parameter_name, (results, parameter) in parameters_info.items():
|
| 94 |
+
(params_without_wd if any(results) else params_with_wd)['params'].append(
|
| 95 |
+
parameter
|
| 96 |
+
)
|
| 97 |
+
return [params_with_wd, params_without_wd]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def make_optimizer(
|
| 101 |
+
config: dict[str, Any],
|
| 102 |
+
parameter_groups,
|
| 103 |
+
) -> optim.Optimizer:
|
| 104 |
+
if config['optimizer'] == 'FT-Transformer-default':
|
| 105 |
+
return optim.AdamW(parameter_groups, lr=1e-4, weight_decay=1e-5)
|
| 106 |
+
return getattr(optim, config['optimizer'])(
|
| 107 |
+
parameter_groups,
|
| 108 |
+
**{x: config[x] for x in ['lr', 'weight_decay', 'momentum'] if x in config},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_lr(optimizer: optim.Optimizer) -> float:
|
| 113 |
+
return next(iter(optimizer.param_groups))['lr']
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def is_oom_exception(err: RuntimeError) -> bool:
|
| 117 |
+
return any(
|
| 118 |
+
x in str(err)
|
| 119 |
+
for x in [
|
| 120 |
+
'CUDA out of memory',
|
| 121 |
+
'CUBLAS_STATUS_ALLOC_FAILED',
|
| 122 |
+
'CUDA error: out of memory',
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def train_with_auto_virtual_batch(
|
| 128 |
+
optimizer,
|
| 129 |
+
loss_fn,
|
| 130 |
+
step,
|
| 131 |
+
batch,
|
| 132 |
+
chunk_size: int,
|
| 133 |
+
) -> tuple[Tensor, int]:
|
| 134 |
+
batch_size = len(batch)
|
| 135 |
+
random_state = zero.random.get_state()
|
| 136 |
+
loss = None
|
| 137 |
+
while chunk_size != 0:
|
| 138 |
+
try:
|
| 139 |
+
zero.random.set_state(random_state)
|
| 140 |
+
optimizer.zero_grad()
|
| 141 |
+
if batch_size <= chunk_size:
|
| 142 |
+
loss = loss_fn(*step(batch))
|
| 143 |
+
loss.backward()
|
| 144 |
+
else:
|
| 145 |
+
loss = None
|
| 146 |
+
for chunk in zero.iter_batches(batch, chunk_size):
|
| 147 |
+
chunk_loss = loss_fn(*step(chunk))
|
| 148 |
+
chunk_loss = chunk_loss * (len(chunk) / batch_size)
|
| 149 |
+
chunk_loss.backward()
|
| 150 |
+
if loss is None:
|
| 151 |
+
loss = chunk_loss.detach()
|
| 152 |
+
else:
|
| 153 |
+
loss += chunk_loss.detach()
|
| 154 |
+
except RuntimeError as err:
|
| 155 |
+
if not is_oom_exception(err):
|
| 156 |
+
raise
|
| 157 |
+
chunk_size //= 2
|
| 158 |
+
else:
|
| 159 |
+
break
|
| 160 |
+
if not chunk_size:
|
| 161 |
+
raise RuntimeError('Not enough memory even for batch_size=1')
|
| 162 |
+
optimizer.step()
|
| 163 |
+
return cast(Tensor, loss), chunk_size
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def process_epoch_losses(losses: list[Tensor]) -> tuple[list[float], float]:
|
| 167 |
+
losses_ = torch.stack(losses).tolist()
|
| 168 |
+
return losses_, statistics.mean(losses_)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Have not used in TabDDPM project.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import datetime
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import typing as ty
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
PROJ = Path('tab-ddpm/').absolute().resolve()
|
| 12 |
+
EXP = PROJ / 'exp'
|
| 13 |
+
DATA = PROJ / 'data'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_path(path: ty.Union[str, Path]) -> Path:
|
| 17 |
+
if isinstance(path, str):
|
| 18 |
+
path = Path(path)
|
| 19 |
+
if not path.is_absolute():
|
| 20 |
+
path = PROJ / path
|
| 21 |
+
return path.resolve()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_relative_path(path: ty.Union[str, Path]) -> Path:
|
| 25 |
+
return get_path(path).relative_to(PROJ)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def duplicate_path(
|
| 29 |
+
src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
|
| 30 |
+
) -> None:
|
| 31 |
+
src = get_path(src)
|
| 32 |
+
alternative_project_dir = get_path(alternative_project_dir)
|
| 33 |
+
dst = alternative_project_dir / src.relative_to(PROJ)
|
| 34 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
if dst.exists():
|
| 36 |
+
dst = dst.with_name(
|
| 37 |
+
dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
|
| 38 |
+
)
|
| 39 |
+
(shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
from typing import Any, Optional, Tuple, Dict, Union, cast
|
| 3 |
+
from functools import partial
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import scipy.special
|
| 7 |
+
import sklearn.metrics as skm
|
| 8 |
+
|
| 9 |
+
from . import util
|
| 10 |
+
from .util import TaskType
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class PredictionType(enum.Enum):
|
| 14 |
+
LOGITS = 'logits'
|
| 15 |
+
PROBS = 'probs'
|
| 16 |
+
|
| 17 |
+
class MetricsReport:
|
| 18 |
+
def __init__(self, report: dict, task_type: TaskType):
|
| 19 |
+
self._res = {k: {} for k in report.keys()}
|
| 20 |
+
if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
|
| 21 |
+
self._metrics_names = ["acc", "f1"]
|
| 22 |
+
for k in report.keys():
|
| 23 |
+
self._res[k]["acc"] = report[k]["accuracy"]
|
| 24 |
+
self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
|
| 25 |
+
if task_type == TaskType.BINCLASS:
|
| 26 |
+
self._res[k]["roc_auc"] = report[k]["roc_auc"]
|
| 27 |
+
self._metrics_names.append("roc_auc")
|
| 28 |
+
|
| 29 |
+
elif task_type == TaskType.REGRESSION:
|
| 30 |
+
self._metrics_names = ["r2", "rmse"]
|
| 31 |
+
for k in report.keys():
|
| 32 |
+
self._res[k]["r2"] = report[k]["r2"]
|
| 33 |
+
self._res[k]["rmse"] = report[k]["rmse"]
|
| 34 |
+
else:
|
| 35 |
+
raise "Unknown TaskType!"
|
| 36 |
+
|
| 37 |
+
def get_splits_names(self) -> list[str]:
|
| 38 |
+
return self._res.keys()
|
| 39 |
+
|
| 40 |
+
def get_metrics_names(self) -> list[str]:
|
| 41 |
+
return self._metrics_names
|
| 42 |
+
|
| 43 |
+
def get_metric(self, split: str, metric: str) -> float:
|
| 44 |
+
return self._res[split][metric]
|
| 45 |
+
|
| 46 |
+
def get_val_score(self) -> float:
|
| 47 |
+
return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
|
| 48 |
+
|
| 49 |
+
def get_test_score(self) -> float:
|
| 50 |
+
return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
|
| 51 |
+
|
| 52 |
+
def print_metrics(self) -> None:
|
| 53 |
+
res = {
|
| 54 |
+
"val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
|
| 55 |
+
"test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
print("*"*100)
|
| 59 |
+
print("[val]")
|
| 60 |
+
print(res["val"])
|
| 61 |
+
print("[test]")
|
| 62 |
+
print(res["test"])
|
| 63 |
+
|
| 64 |
+
return res
|
| 65 |
+
|
| 66 |
+
class SeedsMetricsReport:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self._reports = []
|
| 69 |
+
|
| 70 |
+
def add_report(self, report: MetricsReport) -> None:
|
| 71 |
+
self._reports.append(report)
|
| 72 |
+
|
| 73 |
+
def get_mean_std(self) -> dict:
|
| 74 |
+
res = {k: {} for k in ["train", "val", "test"]}
|
| 75 |
+
for split in self._reports[0].get_splits_names():
|
| 76 |
+
for metric in self._reports[0].get_metrics_names():
|
| 77 |
+
res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
|
| 78 |
+
|
| 79 |
+
agg_res = {k: {} for k in ["train", "val", "test"]}
|
| 80 |
+
for split in self._reports[0].get_splits_names():
|
| 81 |
+
for metric in self._reports[0].get_metrics_names():
|
| 82 |
+
for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
|
| 83 |
+
agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
|
| 84 |
+
self._res = res
|
| 85 |
+
self._agg_res = agg_res
|
| 86 |
+
|
| 87 |
+
return agg_res
|
| 88 |
+
|
| 89 |
+
def print_result(self) -> dict:
|
| 90 |
+
res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
|
| 91 |
+
print("="*100)
|
| 92 |
+
print("EVAL RESULTS:")
|
| 93 |
+
print("[val]")
|
| 94 |
+
print(res["val"])
|
| 95 |
+
print("[test]")
|
| 96 |
+
print(res["test"])
|
| 97 |
+
print("="*100)
|
| 98 |
+
return res
|
| 99 |
+
|
| 100 |
+
def calculate_rmse(
|
| 101 |
+
y_true: np.ndarray, y_pred: np.ndarray, std: Optional[float]
|
| 102 |
+
) -> float:
|
| 103 |
+
rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
|
| 104 |
+
if std is not None:
|
| 105 |
+
rmse *= std
|
| 106 |
+
return rmse
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _get_labels_and_probs(
|
| 110 |
+
y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
|
| 111 |
+
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
|
| 112 |
+
assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
|
| 113 |
+
|
| 114 |
+
if prediction_type is None:
|
| 115 |
+
return y_pred, None
|
| 116 |
+
|
| 117 |
+
if prediction_type == PredictionType.LOGITS:
|
| 118 |
+
probs = (
|
| 119 |
+
scipy.special.expit(y_pred)
|
| 120 |
+
if task_type == TaskType.BINCLASS
|
| 121 |
+
else scipy.special.softmax(y_pred, axis=1)
|
| 122 |
+
)
|
| 123 |
+
elif prediction_type == PredictionType.PROBS:
|
| 124 |
+
probs = y_pred
|
| 125 |
+
else:
|
| 126 |
+
util.raise_unknown('prediction_type', prediction_type)
|
| 127 |
+
|
| 128 |
+
assert probs is not None
|
| 129 |
+
labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
|
| 130 |
+
return labels.astype('int64'), probs
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def calculate_metrics(
|
| 134 |
+
y_true: np.ndarray,
|
| 135 |
+
y_pred: np.ndarray,
|
| 136 |
+
task_type: Union[str, TaskType],
|
| 137 |
+
prediction_type: Optional[Union[str, PredictionType]],
|
| 138 |
+
y_info: Dict[str, Any],
|
| 139 |
+
) -> Dict[str, Any]:
|
| 140 |
+
# Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
|
| 141 |
+
task_type = TaskType(task_type)
|
| 142 |
+
if prediction_type is not None:
|
| 143 |
+
prediction_type = PredictionType(prediction_type)
|
| 144 |
+
|
| 145 |
+
if task_type == TaskType.REGRESSION:
|
| 146 |
+
assert prediction_type is None
|
| 147 |
+
assert 'std' in y_info
|
| 148 |
+
rmse = calculate_rmse(y_true, y_pred, y_info['std'])
|
| 149 |
+
r2 = skm.r2_score(y_true, y_pred)
|
| 150 |
+
result = {'rmse': rmse, 'r2': r2}
|
| 151 |
+
else:
|
| 152 |
+
labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
|
| 153 |
+
result = cast(
|
| 154 |
+
Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
|
| 155 |
+
)
|
| 156 |
+
if task_type == TaskType.BINCLASS:
|
| 157 |
+
result['roc_auc'] = skm.roc_auc_score(y_true, probs)
|
| 158 |
+
return result
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.py
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import atexit
|
| 3 |
+
import enum
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pickle
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
from copy import deepcopy
|
| 12 |
+
from dataclasses import asdict, fields, is_dataclass
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from pprint import pprint
|
| 15 |
+
from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
|
| 16 |
+
|
| 17 |
+
import __main__
|
| 18 |
+
import numpy as np
|
| 19 |
+
import tomli
|
| 20 |
+
import tomli_w
|
| 21 |
+
import torch
|
| 22 |
+
import zero
|
| 23 |
+
|
| 24 |
+
from . import env
|
| 25 |
+
|
| 26 |
+
RawConfig = Dict[str, Any]
|
| 27 |
+
Report = Dict[str, Any]
|
| 28 |
+
T = TypeVar('T')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Part(enum.Enum):
|
| 32 |
+
TRAIN = 'train'
|
| 33 |
+
VAL = 'val'
|
| 34 |
+
TEST = 'test'
|
| 35 |
+
|
| 36 |
+
def __str__(self) -> str:
|
| 37 |
+
return self.value
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TaskType(enum.Enum):
|
| 41 |
+
BINCLASS = 'binclass'
|
| 42 |
+
MULTICLASS = 'multiclass'
|
| 43 |
+
REGRESSION = 'regression'
|
| 44 |
+
|
| 45 |
+
def __str__(self) -> str:
|
| 46 |
+
return self.value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Timer(zero.Timer):
|
| 50 |
+
@classmethod
|
| 51 |
+
def launch(cls) -> 'Timer':
|
| 52 |
+
timer = cls()
|
| 53 |
+
timer.run()
|
| 54 |
+
return timer
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def update_training_log(training_log, data, metrics):
|
| 58 |
+
def _update(log_part, data_part):
|
| 59 |
+
for k, v in data_part.items():
|
| 60 |
+
if isinstance(v, dict):
|
| 61 |
+
_update(log_part.setdefault(k, {}), v)
|
| 62 |
+
elif isinstance(v, list):
|
| 63 |
+
log_part.setdefault(k, []).extend(v)
|
| 64 |
+
else:
|
| 65 |
+
log_part.setdefault(k, []).append(v)
|
| 66 |
+
|
| 67 |
+
_update(training_log, data)
|
| 68 |
+
transposed_metrics = {}
|
| 69 |
+
for part, part_metrics in metrics.items():
|
| 70 |
+
for metric_name, value in part_metrics.items():
|
| 71 |
+
transposed_metrics.setdefault(metric_name, {})[part] = value
|
| 72 |
+
_update(training_log, transposed_metrics)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def raise_unknown(unknown_what: str, unknown_value: Any):
|
| 76 |
+
raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _replace(data, condition, value):
|
| 80 |
+
def do(x):
|
| 81 |
+
if isinstance(x, dict):
|
| 82 |
+
return {k: do(v) for k, v in x.items()}
|
| 83 |
+
elif isinstance(x, list):
|
| 84 |
+
return [do(y) for y in x]
|
| 85 |
+
else:
|
| 86 |
+
return value if condition(x) else x
|
| 87 |
+
|
| 88 |
+
return do(data)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
_CONFIG_NONE = '__none__'
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def unpack_config(config: RawConfig) -> RawConfig:
|
| 95 |
+
config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
|
| 96 |
+
return config
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def pack_config(config: RawConfig) -> RawConfig:
|
| 100 |
+
config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
|
| 101 |
+
return config
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def load_config(path: Union[Path, str]) -> Any:
|
| 105 |
+
with open(path, 'rb') as f:
|
| 106 |
+
return unpack_config(tomli.load(f))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def dump_config(config: Any, path: Union[Path, str]) -> None:
|
| 110 |
+
with open(path, 'wb') as f:
|
| 111 |
+
tomli_w.dump(pack_config(config), f)
|
| 112 |
+
# check that there are no bugs in all these "pack/unpack" things
|
| 113 |
+
assert config == load_config(path)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def load_json(path: Union[Path, str], **kwargs) -> Any:
|
| 117 |
+
return json.loads(Path(path).read_text(), **kwargs)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 121 |
+
kwargs.setdefault('indent', 4)
|
| 122 |
+
Path(path).write_text(json.dumps(x, **kwargs) + '\n')
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def load_pickle(path: Union[Path, str], **kwargs) -> Any:
|
| 126 |
+
return pickle.loads(Path(path).read_bytes(), **kwargs)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 130 |
+
Path(path).write_bytes(pickle.dumps(x, **kwargs))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def load(path: Union[Path, str], **kwargs) -> Any:
|
| 134 |
+
return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
|
| 138 |
+
return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _get_output_item_path(
|
| 142 |
+
path: Union[str, Path], filename: str, must_exist: bool
|
| 143 |
+
) -> Path:
|
| 144 |
+
path = env.get_path(path)
|
| 145 |
+
if path.suffix == '.toml':
|
| 146 |
+
path = path.with_suffix('')
|
| 147 |
+
if path.is_dir():
|
| 148 |
+
path = path / filename
|
| 149 |
+
else:
|
| 150 |
+
assert path.name == filename
|
| 151 |
+
assert path.parent.exists()
|
| 152 |
+
if must_exist:
|
| 153 |
+
assert path.exists()
|
| 154 |
+
return path
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def load_report(path: Path) -> Report:
|
| 158 |
+
return load_json(_get_output_item_path(path, 'report.json', True))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def dump_report(report: dict, path: Path) -> None:
|
| 162 |
+
dump_json(report, _get_output_item_path(path, 'report.json', False))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def load_predictions(path: Path) -> Dict[str, np.ndarray]:
|
| 166 |
+
with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
|
| 167 |
+
return {x: predictions[x] for x in predictions}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
|
| 171 |
+
np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
|
| 175 |
+
dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
|
| 179 |
+
return torch.load(
|
| 180 |
+
_get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def get_device() -> torch.device:
|
| 185 |
+
if torch.cuda.is_available():
|
| 186 |
+
assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
|
| 187 |
+
return torch.device('cuda:0')
|
| 188 |
+
else:
|
| 189 |
+
return torch.device('cpu')
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _print_sep(c, size=100):
|
| 193 |
+
print(c * size)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def start(
|
| 197 |
+
config_cls: Type[T] = RawConfig,
|
| 198 |
+
argv: Optional[List[str]] = None,
|
| 199 |
+
patch_raw_config: Optional[Callable[[RawConfig], None]] = None,
|
| 200 |
+
) -> Tuple[T, Path, Report]: # config # output dir # report
|
| 201 |
+
parser = argparse.ArgumentParser()
|
| 202 |
+
parser.add_argument('config', metavar='FILE')
|
| 203 |
+
parser.add_argument('--force', action='store_true')
|
| 204 |
+
parser.add_argument('--continue', action='store_true', dest='continue_')
|
| 205 |
+
if argv is None:
|
| 206 |
+
program = __main__.__file__
|
| 207 |
+
args = parser.parse_args()
|
| 208 |
+
else:
|
| 209 |
+
program = argv[0]
|
| 210 |
+
try:
|
| 211 |
+
args = parser.parse_args(argv[1:])
|
| 212 |
+
except Exception:
|
| 213 |
+
print(
|
| 214 |
+
'Failed to parse `argv`.'
|
| 215 |
+
' Remember that the first item of `argv` must be the path (relative to'
|
| 216 |
+
' the project root) to the script/notebook.'
|
| 217 |
+
)
|
| 218 |
+
raise
|
| 219 |
+
args = parser.parse_args(argv)
|
| 220 |
+
|
| 221 |
+
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
|
| 222 |
+
if snapshot_dir and Path(snapshot_dir).joinpath('CHECKPOINTS_RESTORED').exists():
|
| 223 |
+
assert args.continue_
|
| 224 |
+
|
| 225 |
+
config_path = env.get_path(args.config)
|
| 226 |
+
output_dir = config_path.with_suffix('')
|
| 227 |
+
_print_sep('=')
|
| 228 |
+
print(f'[output] {output_dir}')
|
| 229 |
+
_print_sep('=')
|
| 230 |
+
|
| 231 |
+
assert config_path.exists()
|
| 232 |
+
raw_config = load_config(config_path)
|
| 233 |
+
if patch_raw_config is not None:
|
| 234 |
+
patch_raw_config(raw_config)
|
| 235 |
+
if is_dataclass(config_cls):
|
| 236 |
+
config = from_dict(config_cls, raw_config)
|
| 237 |
+
full_raw_config = asdict(config)
|
| 238 |
+
else:
|
| 239 |
+
assert config_cls is dict
|
| 240 |
+
full_raw_config = config = raw_config
|
| 241 |
+
full_raw_config = asdict(config)
|
| 242 |
+
|
| 243 |
+
if output_dir.exists():
|
| 244 |
+
if args.force:
|
| 245 |
+
print('Removing the existing output and creating a new one...')
|
| 246 |
+
shutil.rmtree(output_dir)
|
| 247 |
+
output_dir.mkdir()
|
| 248 |
+
elif not args.continue_:
|
| 249 |
+
backup_output(output_dir)
|
| 250 |
+
print('The output directory already exists. Done!\n')
|
| 251 |
+
sys.exit()
|
| 252 |
+
elif output_dir.joinpath('DONE').exists():
|
| 253 |
+
backup_output(output_dir)
|
| 254 |
+
print('The "DONE" file already exists. Done!')
|
| 255 |
+
sys.exit()
|
| 256 |
+
else:
|
| 257 |
+
print('Continuing with the existing output...')
|
| 258 |
+
else:
|
| 259 |
+
print('Creating the output...')
|
| 260 |
+
output_dir.mkdir()
|
| 261 |
+
|
| 262 |
+
report = {
|
| 263 |
+
'program': str(env.get_relative_path(program)),
|
| 264 |
+
'environment': {},
|
| 265 |
+
'config': full_raw_config,
|
| 266 |
+
}
|
| 267 |
+
if torch.cuda.is_available(): # type: ignore[code]
|
| 268 |
+
report['environment'].update(
|
| 269 |
+
{
|
| 270 |
+
'CUDA_VISIBLE_DEVICES': os.environ.get('CUDA_VISIBLE_DEVICES'),
|
| 271 |
+
'gpus': zero.hardware.get_gpus_info(),
|
| 272 |
+
'torch.version.cuda': torch.version.cuda,
|
| 273 |
+
'torch.backends.cudnn.version()': torch.backends.cudnn.version(), # type: ignore[code]
|
| 274 |
+
'torch.cuda.nccl.version()': torch.cuda.nccl.version(), # type: ignore[code]
|
| 275 |
+
}
|
| 276 |
+
)
|
| 277 |
+
dump_report(report, output_dir)
|
| 278 |
+
dump_json(raw_config, output_dir / 'raw_config.json')
|
| 279 |
+
_print_sep('-')
|
| 280 |
+
pprint(full_raw_config, width=100)
|
| 281 |
+
_print_sep('-')
|
| 282 |
+
return cast(config_cls, config), output_dir, report
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
_LAST_SNAPSHOT_TIME = None
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def backup_output(output_dir: Path) -> None:
|
| 289 |
+
backup_dir = os.environ.get('TMP_OUTPUT_PATH')
|
| 290 |
+
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
|
| 291 |
+
if backup_dir is None:
|
| 292 |
+
assert snapshot_dir is None
|
| 293 |
+
return
|
| 294 |
+
assert snapshot_dir is not None
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
relative_output_dir = output_dir.relative_to(env.PROJ)
|
| 298 |
+
except ValueError:
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
for dir_ in [backup_dir, snapshot_dir]:
|
| 302 |
+
new_output_dir = dir_ / relative_output_dir
|
| 303 |
+
prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
|
| 304 |
+
new_output_dir.parent.mkdir(exist_ok=True, parents=True)
|
| 305 |
+
if new_output_dir.exists():
|
| 306 |
+
new_output_dir.rename(prev_backup_output_dir)
|
| 307 |
+
shutil.copytree(output_dir, new_output_dir)
|
| 308 |
+
# the case for evaluate.py which automatically creates configs
|
| 309 |
+
if output_dir.with_suffix('.toml').exists():
|
| 310 |
+
shutil.copyfile(
|
| 311 |
+
output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
|
| 312 |
+
)
|
| 313 |
+
if prev_backup_output_dir.exists():
|
| 314 |
+
shutil.rmtree(prev_backup_output_dir)
|
| 315 |
+
|
| 316 |
+
global _LAST_SNAPSHOT_TIME
|
| 317 |
+
if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
|
| 318 |
+
import nirvana_dl.snapshot # type: ignore[code]
|
| 319 |
+
|
| 320 |
+
nirvana_dl.snapshot.dump_snapshot()
|
| 321 |
+
_LAST_SNAPSHOT_TIME = time.time()
|
| 322 |
+
print('The snapshot was saved!')
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
|
| 326 |
+
return (
|
| 327 |
+
{k: v['score'] for k, v in metrics.items()}
|
| 328 |
+
if 'score' in next(iter(metrics.values()))
|
| 329 |
+
else None
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
|
| 334 |
+
return ' '.join(
|
| 335 |
+
f"[{x}] {metrics[x]['score']:.3f}"
|
| 336 |
+
for x in ['test', 'val', 'train']
|
| 337 |
+
if x in metrics
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def finish(output_dir: Path, report: dict) -> None:
|
| 342 |
+
print()
|
| 343 |
+
_print_sep('=')
|
| 344 |
+
|
| 345 |
+
metrics = report.get('metrics')
|
| 346 |
+
if metrics is not None:
|
| 347 |
+
scores = _get_scores(metrics)
|
| 348 |
+
if scores is not None:
|
| 349 |
+
dump_json(scores, output_dir / 'scores.json')
|
| 350 |
+
print(format_scores(metrics))
|
| 351 |
+
_print_sep('-')
|
| 352 |
+
|
| 353 |
+
dump_report(report, output_dir)
|
| 354 |
+
json_output_path = os.environ.get('JSON_OUTPUT_FILE')
|
| 355 |
+
if json_output_path:
|
| 356 |
+
try:
|
| 357 |
+
key = str(output_dir.relative_to(env.PROJ))
|
| 358 |
+
except ValueError:
|
| 359 |
+
pass
|
| 360 |
+
else:
|
| 361 |
+
json_output_path = Path(json_output_path)
|
| 362 |
+
try:
|
| 363 |
+
json_data = json.loads(json_output_path.read_text())
|
| 364 |
+
except (FileNotFoundError, json.decoder.JSONDecodeError):
|
| 365 |
+
json_data = {}
|
| 366 |
+
json_data[key] = load_json(output_dir / 'report.json')
|
| 367 |
+
json_output_path.write_text(json.dumps(json_data, indent=4))
|
| 368 |
+
shutil.copyfile(
|
| 369 |
+
json_output_path,
|
| 370 |
+
os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
output_dir.joinpath('DONE').touch()
|
| 374 |
+
backup_output(output_dir)
|
| 375 |
+
print(f'Done! | {report.get("time")} | {output_dir}')
|
| 376 |
+
_print_sep('=')
|
| 377 |
+
print()
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def from_dict(datacls: Type[T], data: dict) -> T:
|
| 381 |
+
assert is_dataclass(datacls)
|
| 382 |
+
data = deepcopy(data)
|
| 383 |
+
for field in fields(datacls):
|
| 384 |
+
if field.name not in data:
|
| 385 |
+
continue
|
| 386 |
+
if is_dataclass(field.type):
|
| 387 |
+
data[field.name] = from_dict(field.type, data[field.name])
|
| 388 |
+
elif (
|
| 389 |
+
get_origin(field.type) is Union
|
| 390 |
+
and len(get_args(field.type)) == 2
|
| 391 |
+
and get_args(field.type)[1] is type(None)
|
| 392 |
+
and is_dataclass(get_args(field.type)[0])
|
| 393 |
+
):
|
| 394 |
+
if data[field.name] is not None:
|
| 395 |
+
data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
|
| 396 |
+
return datacls(**data)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def replace_factor_with_value(
|
| 400 |
+
config: RawConfig,
|
| 401 |
+
key: str,
|
| 402 |
+
reference_value: int,
|
| 403 |
+
bounds: Tuple[float, float],
|
| 404 |
+
) -> None:
|
| 405 |
+
factor_key = key + '_factor'
|
| 406 |
+
if factor_key not in config:
|
| 407 |
+
assert key in config
|
| 408 |
+
else:
|
| 409 |
+
assert key not in config
|
| 410 |
+
factor = config.pop(factor_key)
|
| 411 |
+
assert bounds[0] <= factor <= bounds[1]
|
| 412 |
+
config[key] = int(factor * reference_value)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def get_temporary_copy(path: Union[str, Path]) -> Path:
|
| 416 |
+
path = env.get_path(path)
|
| 417 |
+
assert not path.is_dir() and not path.is_symlink()
|
| 418 |
+
tmp_path = path.with_name(
|
| 419 |
+
path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
|
| 420 |
+
)
|
| 421 |
+
shutil.copyfile(path, tmp_path)
|
| 422 |
+
atexit.register(lambda: tmp_path.unlink())
|
| 423 |
+
return tmp_path
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def get_python():
|
| 427 |
+
python = Path('python3.9')
|
| 428 |
+
return str(python) if python.exists() else 'python'
|
| 429 |
+
|
| 430 |
+
def get_catboost_config(real_data_path, is_cv=False):
|
| 431 |
+
ds_name = Path(real_data_path).name
|
| 432 |
+
C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
|
| 433 |
+
return C
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
catboost==1.0.3
|
| 2 |
+
category-encoders==2.3.0
|
| 3 |
+
dython==0.5.1
|
| 4 |
+
icecream==2.1.2
|
| 5 |
+
libzero==0.0.8
|
| 6 |
+
numpy==1.21.4
|
| 7 |
+
optuna==2.10.1
|
| 8 |
+
pandas==1.3.4
|
| 9 |
+
pyarrow==6.0.0
|
| 10 |
+
rtdl==0.0.9
|
| 11 |
+
scikit-learn==1.0.2
|
| 12 |
+
scipy==1.7.2
|
| 13 |
+
skorch==0.11.0
|
| 14 |
+
tomli-w==0.4.0
|
| 15 |
+
tomli==1.2.2
|
| 16 |
+
tqdm==4.62.3
|
| 17 |
+
|
| 18 |
+
# smote
|
| 19 |
+
imbalanced-learn==0.7.0
|
| 20 |
+
|
| 21 |
+
# tvae
|
| 22 |
+
rdt==0.6.4
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -e
|
| 3 |
+
cd /data/jialinzhang/synthetic_benchmark/tabddpm/code
|
| 4 |
+
export PYTHONPATH="$PWD:$PYTHONPATH"
|
| 5 |
+
python -m scripts.pipeline "$@"
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -e
|
| 3 |
+
cd /workspace/tabddpm/code
|
| 4 |
+
export PYTHONPATH="$PWD:$PYTHONPATH"
|
| 5 |
+
python -m scripts.pipeline "$@"
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.py
ADDED
|
File without changes
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (219 Bytes). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_catboost.cpython-311.pyc
ADDED
|
Binary file (6.96 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_mlp.cpython-311.pyc
ADDED
|
Binary file (9.61 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/eval_simple.cpython-311.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/sample.cpython-311.pyc
ADDED
|
Binary file (8.3 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/train.cpython-311.pyc
ADDED
|
Binary file (8.15 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__pycache__/utils_train.cpython-311.pyc
ADDED
|
Binary file (4.33 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from catboost import CatBoostClassifier, CatBoostRegressor
|
| 2 |
+
from sklearn.metrics import classification_report, r2_score
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
from sklearn.utils import shuffle
|
| 6 |
+
import zero
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import lib
|
| 9 |
+
from pprint import pprint
|
| 10 |
+
from lib import concat_features, read_pure_data, get_catboost_config, read_changed_val
|
| 11 |
+
|
| 12 |
+
def train_catboost(
|
| 13 |
+
parent_dir,
|
| 14 |
+
real_data_path,
|
| 15 |
+
eval_type,
|
| 16 |
+
T_dict,
|
| 17 |
+
seed = 0,
|
| 18 |
+
params = None,
|
| 19 |
+
change_val = True,
|
| 20 |
+
device = None # dummy
|
| 21 |
+
):
|
| 22 |
+
zero.improve_reproducibility(seed)
|
| 23 |
+
if eval_type != "real":
|
| 24 |
+
synthetic_data_path = os.path.join(parent_dir)
|
| 25 |
+
info = lib.load_json(os.path.join(real_data_path, 'info.json'))
|
| 26 |
+
T = lib.Transformations(**T_dict)
|
| 27 |
+
|
| 28 |
+
if change_val:
|
| 29 |
+
X_num_real, X_cat_real, y_real, X_num_val, X_cat_val, y_val = read_changed_val(real_data_path, val_size=0.2)
|
| 30 |
+
|
| 31 |
+
X = None
|
| 32 |
+
print('-'*100)
|
| 33 |
+
if eval_type == 'merged':
|
| 34 |
+
print('loading merged data...')
|
| 35 |
+
if not change_val:
|
| 36 |
+
X_num_real, X_cat_real, y_real = read_pure_data(real_data_path)
|
| 37 |
+
X_num_fake, X_cat_fake, y_fake = read_pure_data(synthetic_data_path)
|
| 38 |
+
|
| 39 |
+
###
|
| 40 |
+
# dists = privacy_metrics(real_data_path, synthetic_data_path)
|
| 41 |
+
# bad_fakes = dists.argsort()[:int(0.25 * len(y_fake))]
|
| 42 |
+
# X_num_fake = np.delete(X_num_fake, bad_fakes, axis=0)
|
| 43 |
+
# X_cat_fake = np.delete(X_cat_fake, bad_fakes, axis=0) if X_cat_fake is not None else None
|
| 44 |
+
# y_fake = np.delete(y_fake, bad_fakes, axis=0)
|
| 45 |
+
###
|
| 46 |
+
|
| 47 |
+
y = np.concatenate([y_real, y_fake], axis=0)
|
| 48 |
+
|
| 49 |
+
X_num = None
|
| 50 |
+
if X_num_real is not None:
|
| 51 |
+
X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
|
| 52 |
+
|
| 53 |
+
X_cat = None
|
| 54 |
+
if X_cat_real is not None:
|
| 55 |
+
X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
|
| 56 |
+
|
| 57 |
+
elif eval_type == 'synthetic':
|
| 58 |
+
print(f'loading synthetic data: {parent_dir}')
|
| 59 |
+
X_num, X_cat, y = read_pure_data(synthetic_data_path)
|
| 60 |
+
|
| 61 |
+
elif eval_type == 'real':
|
| 62 |
+
print('loading real data...')
|
| 63 |
+
if not change_val:
|
| 64 |
+
X_num, X_cat, y = read_pure_data(real_data_path)
|
| 65 |
+
else:
|
| 66 |
+
raise "Choose eval method"
|
| 67 |
+
|
| 68 |
+
if not change_val:
|
| 69 |
+
X_num_val, X_cat_val, y_val = read_pure_data(real_data_path, 'val')
|
| 70 |
+
X_num_test, X_cat_test, y_test = read_pure_data(real_data_path, 'test')
|
| 71 |
+
|
| 72 |
+
D = lib.Dataset(
|
| 73 |
+
{'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None,
|
| 74 |
+
{'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None,
|
| 75 |
+
{'train': y, 'val': y_val, 'test': y_test},
|
| 76 |
+
{},
|
| 77 |
+
lib.TaskType(info['task_type']),
|
| 78 |
+
info.get('n_classes')
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
D = lib.transform_dataset(D, T, None)
|
| 82 |
+
X = concat_features(D)
|
| 83 |
+
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
|
| 84 |
+
|
| 85 |
+
if params is None:
|
| 86 |
+
catboost_config = get_catboost_config(real_data_path, is_cv=True)
|
| 87 |
+
else:
|
| 88 |
+
catboost_config = params
|
| 89 |
+
|
| 90 |
+
if 'cat_features' not in catboost_config:
|
| 91 |
+
catboost_config['cat_features'] = list(range(D.n_num_features, D.n_features))
|
| 92 |
+
|
| 93 |
+
for col in range(D.n_features):
|
| 94 |
+
for split in X.keys():
|
| 95 |
+
if col in catboost_config['cat_features']:
|
| 96 |
+
X[split][col] = X[split][col].astype(str)
|
| 97 |
+
else:
|
| 98 |
+
X[split][col] = X[split][col].astype(float)
|
| 99 |
+
print(T_dict)
|
| 100 |
+
pprint(catboost_config, width=100)
|
| 101 |
+
print('-'*100)
|
| 102 |
+
|
| 103 |
+
if D.is_regression:
|
| 104 |
+
model = CatBoostRegressor(
|
| 105 |
+
**catboost_config,
|
| 106 |
+
eval_metric='RMSE',
|
| 107 |
+
random_seed=seed
|
| 108 |
+
)
|
| 109 |
+
predict = model.predict
|
| 110 |
+
else:
|
| 111 |
+
model = CatBoostClassifier(
|
| 112 |
+
loss_function="MultiClass" if D.is_multiclass else "Logloss",
|
| 113 |
+
**catboost_config,
|
| 114 |
+
eval_metric='TotalF1',
|
| 115 |
+
random_seed=seed,
|
| 116 |
+
class_names=[str(i) for i in range(D.n_classes)] if D.is_multiclass else ["0", "1"]
|
| 117 |
+
)
|
| 118 |
+
predict = (
|
| 119 |
+
model.predict_proba
|
| 120 |
+
if D.is_multiclass
|
| 121 |
+
else lambda x: model.predict_proba(x)[:, 1]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
model.fit(
|
| 125 |
+
X['train'], D.y['train'],
|
| 126 |
+
eval_set=(X['val'], D.y['val']),
|
| 127 |
+
verbose=100
|
| 128 |
+
)
|
| 129 |
+
predictions = {k: predict(v) for k, v in X.items()}
|
| 130 |
+
print(predictions['train'].shape)
|
| 131 |
+
|
| 132 |
+
report = {}
|
| 133 |
+
report['eval_type'] = eval_type
|
| 134 |
+
report['dataset'] = real_data_path
|
| 135 |
+
report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
|
| 136 |
+
|
| 137 |
+
metrics_report = lib.MetricsReport(report['metrics'], D.task_type)
|
| 138 |
+
metrics_report.print_metrics()
|
| 139 |
+
|
| 140 |
+
if parent_dir is not None:
|
| 141 |
+
lib.dump_json(report, os.path.join(parent_dir, "results_catboost.json"))
|
| 142 |
+
|
| 143 |
+
return metrics_report
|
| 144 |
+
|
| 145 |
+
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.metrics import classification_report, r2_score, f1_score
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
from sklearn.utils import shuffle
|
| 5 |
+
import zero
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import lib
|
| 8 |
+
from tab_ddpm.modules import MLP
|
| 9 |
+
from skorch.regressor import NeuralNetRegressor
|
| 10 |
+
from skorch.classifier import NeuralNetClassifier
|
| 11 |
+
from skorch.dataset import Dataset as SkDataset
|
| 12 |
+
from skorch.callbacks import EarlyStopping, EpochScoring
|
| 13 |
+
from skorch.helper import predefined_split
|
| 14 |
+
from torch.optim import AdamW
|
| 15 |
+
from torch.nn import MSELoss, BCEWithLogitsLoss, CrossEntropyLoss
|
| 16 |
+
|
| 17 |
+
def train_mlp(
|
| 18 |
+
parent_dir,
|
| 19 |
+
real_data_path,
|
| 20 |
+
eval_type,
|
| 21 |
+
T_dict,
|
| 22 |
+
params = None,
|
| 23 |
+
change_val = False,
|
| 24 |
+
seed = 0,
|
| 25 |
+
device = "cuda:0"
|
| 26 |
+
):
|
| 27 |
+
zero.improve_reproducibility(seed)
|
| 28 |
+
synthetic_data_path = os.path.join(parent_dir) if parent_dir is not None else None
|
| 29 |
+
info = lib.load_json(os.path.join(real_data_path, 'info.json'))
|
| 30 |
+
T = lib.Transformations(**T_dict)
|
| 31 |
+
|
| 32 |
+
if change_val:
|
| 33 |
+
X_num_real, X_cat_real, y_real, X_num_val, X_cat_val, y_val = lib.read_changed_val(real_data_path, val_size=0.2)
|
| 34 |
+
|
| 35 |
+
X = None
|
| 36 |
+
print('-'*100)
|
| 37 |
+
if eval_type == 'merged':
|
| 38 |
+
print('loading merged data...')
|
| 39 |
+
if not change_val:
|
| 40 |
+
X_num_real, X_cat_real, y_real = lib.read_pure_data(real_data_path)
|
| 41 |
+
X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(synthetic_data_path)
|
| 42 |
+
y = np.concatenate([y_real, y_fake], axis=0)
|
| 43 |
+
|
| 44 |
+
X_num = None
|
| 45 |
+
if X_num_real is not None:
|
| 46 |
+
X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
|
| 47 |
+
|
| 48 |
+
X_cat = None
|
| 49 |
+
if X_cat_real is not None:
|
| 50 |
+
X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
|
| 51 |
+
|
| 52 |
+
elif eval_type == 'synthetic':
|
| 53 |
+
print('loading synthetic data...')
|
| 54 |
+
X_num, X_cat, y = lib.read_pure_data(synthetic_data_path)
|
| 55 |
+
|
| 56 |
+
elif eval_type == 'real':
|
| 57 |
+
print('loading real data...')
|
| 58 |
+
if not change_val:
|
| 59 |
+
X_num, X_cat, y = lib.read_pure_data(real_data_path)
|
| 60 |
+
else:
|
| 61 |
+
raise "Choose eval method"
|
| 62 |
+
|
| 63 |
+
if not change_val:
|
| 64 |
+
X_num_val, X_cat_val, y_val = lib.read_pure_data(real_data_path, 'val')
|
| 65 |
+
X_num_test, X_cat_test, y_test = lib.read_pure_data(real_data_path, 'test')
|
| 66 |
+
|
| 67 |
+
D = lib.Dataset(
|
| 68 |
+
{'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None,
|
| 69 |
+
{'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None,
|
| 70 |
+
{'train': y, 'val': y_val, 'test': y_test},
|
| 71 |
+
{},
|
| 72 |
+
lib.TaskType(info['task_type']),
|
| 73 |
+
info.get('n_classes')
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
D = lib.transform_dataset(D, T, None)
|
| 77 |
+
X = lib.concat_features(D)
|
| 78 |
+
|
| 79 |
+
X["train"], D.y["train"] = shuffle(X["train"], D.y["train"], random_state=seed)
|
| 80 |
+
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
|
| 81 |
+
|
| 82 |
+
if params is None:
|
| 83 |
+
params = lib.load_json(f"tuned_models/mlp/{Path(real_data_path).name}_cv.json")
|
| 84 |
+
|
| 85 |
+
mlp_params = {}
|
| 86 |
+
if params is not None:
|
| 87 |
+
mlp_params["d_layers"] = params["d_layers"]
|
| 88 |
+
mlp_params["dropout"] = params["dropout"]
|
| 89 |
+
# mlp_params["n_blocks"] = params["n_blocks"]
|
| 90 |
+
# mlp_params["d_main"] = params["d_main"]
|
| 91 |
+
# mlp_params["d_hidden"] = params["d_hidden"]
|
| 92 |
+
# mlp_params["dropout_first"] = params["dropout_first"]
|
| 93 |
+
# mlp_params["dropout_second"] = params["dropout_second"]
|
| 94 |
+
mlp_params["d_in"] = X["train"].shape[1]
|
| 95 |
+
mlp_params["d_out"] = D.nn_output_dim
|
| 96 |
+
|
| 97 |
+
model = MLP.make_baseline(**mlp_params)
|
| 98 |
+
|
| 99 |
+
if D.is_regression:
|
| 100 |
+
y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y}
|
| 101 |
+
elif D.is_binclass:
|
| 102 |
+
y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y}
|
| 103 |
+
else:
|
| 104 |
+
y = {k: D.y[k].astype(np.int64) for k in D.y}
|
| 105 |
+
|
| 106 |
+
train_ds = SkDataset(X = X["train"].to_numpy(), y = y["train"])
|
| 107 |
+
val_ds = SkDataset(X = X["val"].to_numpy(), y = y["val"])
|
| 108 |
+
es = EarlyStopping(monitor="valid_loss", patience=16)
|
| 109 |
+
|
| 110 |
+
print('-'*100)
|
| 111 |
+
|
| 112 |
+
def f1(net, X, y):
|
| 113 |
+
y_pred = net.predict(X)
|
| 114 |
+
return f1_score(y, y_pred, average="macro")
|
| 115 |
+
|
| 116 |
+
def r2(net, X, y):
|
| 117 |
+
y_pred = net.predict(X)
|
| 118 |
+
return r2_score(y, y_pred)
|
| 119 |
+
|
| 120 |
+
if D.is_regression:
|
| 121 |
+
net = NeuralNetRegressor(
|
| 122 |
+
model,
|
| 123 |
+
criterion=MSELoss,
|
| 124 |
+
optimizer=AdamW,
|
| 125 |
+
lr=params["lr"],
|
| 126 |
+
optimizer__weight_decay=params["weight_decay"],
|
| 127 |
+
batch_size=128 if len(D.y["train"]) < 10_000 else 256,
|
| 128 |
+
max_epochs=1000,
|
| 129 |
+
train_split=predefined_split(val_ds),
|
| 130 |
+
iterator_train__shuffle=True,
|
| 131 |
+
device=device,
|
| 132 |
+
callbacks=[es, EpochScoring(r2, lower_is_better=False)],
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
else:
|
| 136 |
+
net = NeuralNetClassifier(
|
| 137 |
+
model,
|
| 138 |
+
criterion=BCEWithLogitsLoss if D.is_binclass else CrossEntropyLoss,
|
| 139 |
+
optimizer=AdamW,
|
| 140 |
+
lr=params["lr"],
|
| 141 |
+
optimizer__weight_decay=params["weight_decay"],
|
| 142 |
+
batch_size=128 if len(D.y["train"]) < 10_000 else 256,
|
| 143 |
+
max_epochs=1000,
|
| 144 |
+
train_split=predefined_split(val_ds),
|
| 145 |
+
iterator_train__shuffle=True,
|
| 146 |
+
device=device,
|
| 147 |
+
callbacks=[es, EpochScoring(f1, lower_is_better=False)],
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
net.fit(
|
| 151 |
+
X=train_ds.X,
|
| 152 |
+
y=train_ds.y
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
print("LAST:", len(net.history))
|
| 156 |
+
|
| 157 |
+
predictions = {k: net.predict_proba(v.to_numpy())[:, 1] if D.is_binclass else
|
| 158 |
+
net.predict_proba(v.to_numpy()) if D.is_multiclass else
|
| 159 |
+
net.predict(v.to_numpy())
|
| 160 |
+
for k, v in X.items()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
report = {}
|
| 164 |
+
report['eval_type'] = eval_type
|
| 165 |
+
report['dataset'] = real_data_path
|
| 166 |
+
report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
|
| 167 |
+
|
| 168 |
+
metrics_report = lib.MetricsReport(report['metrics'], D.task_type)
|
| 169 |
+
metrics_report.print_metrics()
|
| 170 |
+
|
| 171 |
+
if parent_dir is not None:
|
| 172 |
+
lib.dump_json(report, os.path.join(parent_dir, "results_mlp.json"))
|
| 173 |
+
|
| 174 |
+
return metrics_report
|
| 175 |
+
|
| 176 |
+
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from scripts.eval_catboost import train_catboost
|
| 10 |
+
from scripts.eval_mlp import train_mlp
|
| 11 |
+
from scripts.eval_simple import train_simple
|
| 12 |
+
|
| 13 |
+
pipeline = {
|
| 14 |
+
'ddpm': 'scripts/pipeline.py',
|
| 15 |
+
'smote': 'smote/pipeline_smote.py',
|
| 16 |
+
'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py',
|
| 17 |
+
'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabgan.py',
|
| 18 |
+
'tvae': 'CTGAN/pipeline_tvae.py'
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
def eval_seeds(
|
| 22 |
+
raw_config,
|
| 23 |
+
n_seeds,
|
| 24 |
+
eval_type,
|
| 25 |
+
sampling_method="ddpm",
|
| 26 |
+
model_type="catboost",
|
| 27 |
+
n_datasets=1,
|
| 28 |
+
dump=True,
|
| 29 |
+
change_val=False
|
| 30 |
+
):
|
| 31 |
+
|
| 32 |
+
metrics_seeds_report = lib.SeedsMetricsReport()
|
| 33 |
+
parent_dir = Path(raw_config["parent_dir"])
|
| 34 |
+
|
| 35 |
+
if eval_type == 'real':
|
| 36 |
+
n_datasets = 1
|
| 37 |
+
|
| 38 |
+
temp_config = deepcopy(raw_config)
|
| 39 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 40 |
+
dir_ = Path(dir_)
|
| 41 |
+
temp_config["parent_dir"] = str(dir_)
|
| 42 |
+
if sampling_method == "ddpm":
|
| 43 |
+
shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"])
|
| 44 |
+
elif sampling_method in ["ctabgan", "ctabgan-plus"]:
|
| 45 |
+
shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"])
|
| 46 |
+
elif sampling_method == "tvae":
|
| 47 |
+
shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
|
| 48 |
+
|
| 49 |
+
for sample_seed in range(n_datasets):
|
| 50 |
+
temp_config['sample']['seed'] = sample_seed
|
| 51 |
+
lib.dump_config(temp_config, dir_ / "config.toml")
|
| 52 |
+
if eval_type != 'real' and n_datasets > 1:
|
| 53 |
+
subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
|
| 54 |
+
|
| 55 |
+
T_dict = deepcopy(raw_config['eval']['T'])
|
| 56 |
+
for seed in range(n_seeds):
|
| 57 |
+
print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**')
|
| 58 |
+
if model_type == "catboost":
|
| 59 |
+
T_dict["normalization"] = None
|
| 60 |
+
T_dict["cat_encoding"] = None
|
| 61 |
+
metric_report = train_catboost(
|
| 62 |
+
parent_dir=temp_config['parent_dir'],
|
| 63 |
+
real_data_path=temp_config['real_data_path'],
|
| 64 |
+
eval_type=eval_type,
|
| 65 |
+
T_dict=T_dict,
|
| 66 |
+
seed=seed,
|
| 67 |
+
change_val=change_val
|
| 68 |
+
)
|
| 69 |
+
elif model_type == "mlp":
|
| 70 |
+
T_dict["normalization"] = "quantile"
|
| 71 |
+
T_dict["cat_encoding"] = "one-hot"
|
| 72 |
+
metric_report = train_mlp(
|
| 73 |
+
parent_dir=temp_config['parent_dir'],
|
| 74 |
+
real_data_path=temp_config['real_data_path'],
|
| 75 |
+
eval_type=eval_type,
|
| 76 |
+
T_dict=T_dict,
|
| 77 |
+
seed=seed,
|
| 78 |
+
change_val=change_val
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
metrics_seeds_report.add_report(metric_report)
|
| 82 |
+
|
| 83 |
+
metrics_seeds_report.get_mean_std()
|
| 84 |
+
res = metrics_seeds_report.print_result()
|
| 85 |
+
if os.path.exists(parent_dir/ f"eval_{model_type}.json"):
|
| 86 |
+
eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json")
|
| 87 |
+
eval_dict = eval_dict | {eval_type: res}
|
| 88 |
+
else:
|
| 89 |
+
eval_dict = {eval_type: res}
|
| 90 |
+
|
| 91 |
+
if dump:
|
| 92 |
+
lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
|
| 93 |
+
|
| 94 |
+
raw_config['sample']['seed'] = 0
|
| 95 |
+
lib.dump_config(raw_config, parent_dir / 'config.toml')
|
| 96 |
+
return res
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
parser = argparse.ArgumentParser()
|
| 100 |
+
parser.add_argument('--config', metavar='FILE')
|
| 101 |
+
parser.add_argument('n_seeds', type=int, default=10)
|
| 102 |
+
parser.add_argument('sampling_method', type=str, default="ddpm")
|
| 103 |
+
parser.add_argument('eval_type', type=str, default='synthetic')
|
| 104 |
+
parser.add_argument('model_type', type=str, default='catboost')
|
| 105 |
+
parser.add_argument('n_datasets', type=int, default=1)
|
| 106 |
+
parser.add_argument('--no_dump', action='store_false', default=True)
|
| 107 |
+
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
raw_config = lib.load_config(args.config)
|
| 110 |
+
eval_seeds(
|
| 111 |
+
raw_config,
|
| 112 |
+
n_seeds=args.n_seeds,
|
| 113 |
+
sampling_method=args.sampling_method,
|
| 114 |
+
eval_type=args.eval_type,
|
| 115 |
+
model_type=args.model_type,
|
| 116 |
+
n_datasets=args.n_datasets,
|
| 117 |
+
dump=args.no_dump
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from eval_simple import train_simple
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import shutil
|
| 12 |
+
|
| 13 |
+
pipeline = {
|
| 14 |
+
'ddpm': 'scripts/pipeline.py',
|
| 15 |
+
'smote': 'smote/pipeline_smote.py',
|
| 16 |
+
'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py',
|
| 17 |
+
'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabganp.py',
|
| 18 |
+
'tvae': 'CTGAN/pipeline_tvae.py'
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def eval_seeds(
|
| 23 |
+
raw_config,
|
| 24 |
+
n_seeds,
|
| 25 |
+
eval_type,
|
| 26 |
+
sampling_method="ddpm",
|
| 27 |
+
model_type="simple",
|
| 28 |
+
n_datasets=1,
|
| 29 |
+
dump=True,
|
| 30 |
+
change_val=False
|
| 31 |
+
):
|
| 32 |
+
parent_dir = Path(raw_config["parent_dir"])
|
| 33 |
+
models = ["tree", "lr", "rf", "mlp"]
|
| 34 |
+
metrics_seeds_report = {
|
| 35 |
+
k: lib.SeedsMetricsReport() for k in models
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
if eval_type == 'real':
|
| 39 |
+
n_datasets = 1
|
| 40 |
+
|
| 41 |
+
T_dict = deepcopy(raw_config['eval']['T'])
|
| 42 |
+
T_dict["normalization"] = "minmax"
|
| 43 |
+
T_dict["cat_encoding"] = None
|
| 44 |
+
|
| 45 |
+
temp_config = deepcopy(raw_config)
|
| 46 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 47 |
+
dir_ = Path(dir_)
|
| 48 |
+
temp_config["parent_dir"] = str(dir_)
|
| 49 |
+
if sampling_method == "ddpm":
|
| 50 |
+
shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"])
|
| 51 |
+
elif sampling_method in ["ctabgan", "ctabgan-plus"]:
|
| 52 |
+
shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"])
|
| 53 |
+
elif sampling_method == "tvae":
|
| 54 |
+
shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
|
| 55 |
+
|
| 56 |
+
for sample_seed in range(n_datasets):
|
| 57 |
+
temp_config['sample']['seed'] = sample_seed
|
| 58 |
+
lib.dump_config(temp_config, dir_ / "config.toml")
|
| 59 |
+
if eval_type != 'real':
|
| 60 |
+
subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
|
| 61 |
+
|
| 62 |
+
for seed in range(n_seeds):
|
| 63 |
+
print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**')
|
| 64 |
+
for model in models:
|
| 65 |
+
metric_report = train_simple(
|
| 66 |
+
parent_dir=temp_config['parent_dir'],
|
| 67 |
+
real_data_path=temp_config['real_data_path'],
|
| 68 |
+
model_name=model,
|
| 69 |
+
eval_type=eval_type,
|
| 70 |
+
T_dict=T_dict,
|
| 71 |
+
seed=seed,
|
| 72 |
+
change_val=change_val
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
metrics_seeds_report[model].add_report(metric_report)
|
| 76 |
+
for k in models:
|
| 77 |
+
metrics_seeds_report[k].get_mean_std()
|
| 78 |
+
res = {
|
| 79 |
+
k: metrics_seeds_report[k].print_result() for k in models
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
m1, m2 = ("r2-mean", "rmse-mean") if "r2-mean" in res["tree"]["val"] else ("f1-mean", "acc-mean")
|
| 83 |
+
res["avg"] = {
|
| 84 |
+
"val": {
|
| 85 |
+
m1: np.around(np.mean([res[k]["val"][m1] for k in models]), 4),
|
| 86 |
+
m2: np.around(np.mean([res[k]["val"][m2] for k in models]), 4)
|
| 87 |
+
},
|
| 88 |
+
"test": {
|
| 89 |
+
m1: np.around(np.mean([res[k]["test"][m1] for k in models]), 4),
|
| 90 |
+
m2: np.around(np.mean([res[k]["test"][m2] for k in models]), 4)
|
| 91 |
+
},
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if os.path.exists(parent_dir / f"eval_{model_type}.json"):
|
| 95 |
+
eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json")
|
| 96 |
+
eval_dict = eval_dict | {eval_type: res}
|
| 97 |
+
else:
|
| 98 |
+
eval_dict = {eval_type: res}
|
| 99 |
+
|
| 100 |
+
if dump:
|
| 101 |
+
lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
|
| 102 |
+
|
| 103 |
+
raw_config['sample']['seed'] = 0
|
| 104 |
+
lib.dump_config(raw_config, parent_dir / 'config.toml')
|
| 105 |
+
return res
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
parser = argparse.ArgumentParser()
|
| 109 |
+
parser.add_argument('--config', metavar='FILE')
|
| 110 |
+
parser.add_argument('n_seeds', type=int, default=10)
|
| 111 |
+
parser.add_argument('sampling_method', type=str, default="ddpm")
|
| 112 |
+
parser.add_argument('eval_type', type=str, default='synthetic')
|
| 113 |
+
parser.add_argument('model_type', type=str, default='catboost')
|
| 114 |
+
parser.add_argument('n_datasets', type=int, default=1)
|
| 115 |
+
parser.add_argument('--no_dump', action='store_false', default=True)
|
| 116 |
+
|
| 117 |
+
args = parser.parse_args()
|
| 118 |
+
raw_config = lib.load_config(args.config)
|
| 119 |
+
eval_seeds(
|
| 120 |
+
raw_config,
|
| 121 |
+
n_seeds=args.n_seeds,
|
| 122 |
+
sampling_method=args.sampling_method,
|
| 123 |
+
eval_type=args.eval_type,
|
| 124 |
+
model_type=args.model_type,
|
| 125 |
+
n_datasets=args.n_datasets,
|
| 126 |
+
dump=args.no_dump
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if __name__ == '__main__':
|
| 130 |
+
main()
|