-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsamples.py
More file actions
2025 lines (1717 loc) · 69.6 KB
/
Copy pathsamples.py
File metadata and controls
2025 lines (1717 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######################################################################################
# Copyright (c) 2023-2025 Orange. All rights reserved. #
# This software is distributed under the BSD 3-Clause-clear License, the text of #
# which is available at https://spdx.org/licenses/BSD-3-Clause-Clear.html or #
# see the "LICENSE.md" file for more details. #
######################################################################################
"""Khiops Python samples
The functions in this script demonstrate the basic use of the khiops library.
This script is fully compatible with the latest Khiops version. If you are using an
older version some samples may fail.
"""
import argparse
import khiops
import os
from khiops import core as kh
# Disable open files without encoding because samples are simple code snippets
# pylint: disable=unspecified-encoding
# For ease of use the functions in this module contain (repeated) import statements
# We disable all pylint warnings related to imports
# pylint: disable=import-outside-toplevel,redefined-outer-name,reimported
def get_khiops_version():
"""Shows the Khiops version"""
print(f"Khiops version: {kh.get_khiops_version()}")
def export_dictionary_as_json():
"""Exports a dictionary file ('.kdic') in JSON format ('.kdicj')"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
json_dictionary_file_path = os.path.join(
"kh_samples",
"export_dictionary_as_json",
"Adult.kdicj",
)
# Export the input dictionary as JSON
kh.export_dictionary_as_json(dictionary_file_path, json_dictionary_file_path)
def build_dictionary_from_data_table():
"""Automatically creates a dictionary file from a data table"""
# Imports
import os
from khiops import core as kh
# Set the file paths
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
dictionary_name = "AutoAdult"
dictionary_file_path = os.path.join(
"kh_samples", "build_dictionary_from_data_table", "AutoAdult.kdic"
)
# Create the dictionary from the data table
kh.build_dictionary_from_data_table(
data_table_path, dictionary_name, dictionary_file_path
)
def detect_data_table_format():
"""Detects the format of a data table with and without a dictionary file
The user may provide a dictionary file or dictionary domain object specifying the
table schema. The detection heuristic is more accurate with this information.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
output_dir = os.path.join("kh_samples", "detect_data_table_format")
transformed_data_table_path = os.path.join(output_dir, "AdultWithAnotherFormat.txt")
# Create the output directory
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
# Detect the format of the table
format_spec = kh.detect_data_table_format(data_table_path)
print("Format specification (header_line, field_separator)")
print("Format detected on original table:", format_spec)
# Make a deployment to change the format of the data table
kh.deploy_model(
dictionary_file_path,
"Adult",
data_table_path,
transformed_data_table_path,
output_header_line=False,
output_field_separator=",",
)
# Detect the new format of the table without a dictionary file
format_spec = kh.detect_data_table_format(transformed_data_table_path)
print("Format detected on reformatted table:", format_spec)
# Detect the new format of the table with a dictionary file
format_spec = kh.detect_data_table_format(
transformed_data_table_path,
dictionary_file_path_or_domain=dictionary_file_path,
dictionary_name="Adult",
)
print("Format detected (with dictionary file) on reformatted table:", format_spec)
def check_database():
"""Runs an integrity check of a database
The results are stored in the specified log file with at most 50 error messages.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
log_file = os.path.join("kh_samples", "check_database", "check_database.log")
# Check the database
kh.check_database(
dictionary_file_path,
"Adult",
data_table_path,
log_file_path=log_file,
max_messages=50,
)
def export_dictionary_files():
"""Exports a customized dictionary to ".kdic" and to ".kdicj" (JSON)"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
output_dir = os.path.join("kh_samples", "export_dictionary_file")
output_dictionary_file_path = os.path.join(output_dir, "ModifiedAdult.kdic")
output_dictionary_json_path = os.path.join(output_dir, "ModifiedAdult.kdicj")
alt_output_dictionary_json_path = os.path.join(output_dir, "AltModifiedAdult.kdicj")
# Load the dictionary domain from initial dictionary file
# Then obtain the "Adult" dictionary within
domain = kh.read_dictionary_file(dictionary_file_path)
dictionary = domain.get_dictionary("Adult")
# Set some of its variables to unused
fnlwgt_variable = dictionary.get_variable("fnlwgt")
fnlwgt_variable.used = False
label_variable = dictionary.get_variable("Label")
label_variable.used = False
# Create output directory if necessary
if not os.path.exists("kh_samples"):
os.mkdir("kh_samples")
os.mkdir(output_dir)
else:
if not os.path.exists(output_dir):
os.mkdir(output_dir)
# Export to kdic
domain.export_khiops_dictionary_file(output_dictionary_file_path)
# Export to kdicj either from the domain or from a kdic file
# Requires a Khiops execution, that's why it is not a method of DictionaryDomain
kh.export_dictionary_as_json(domain, output_dictionary_json_path)
kh.export_dictionary_as_json(
output_dictionary_file_path, alt_output_dictionary_json_path
)
def train_predictor():
"""Trains a predictor with a minimal setup"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
analysis_report_file_path = os.path.join(
"kh_samples", "train_predictor", "AnalysisReport.khj"
)
# Train the predictor
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
analysis_report_file_path,
max_trees=0,
)
def train_predictor_file_paths():
"""Trains a predictor and stores the return value of the function"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples", "train_predictor_file_paths", "AnalysisResults.khj"
)
# Train the predictor
_, modeling_dictionary_file_path = kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
max_trees=0,
)
print("Reports file available at " + report_file_path)
print("Modeling dictionary file available at " + modeling_dictionary_file_path)
# If you have Khiops Visualization installed you may open the report as follows
# kh.visualize_report(report_file_path)
def train_predictor_text():
"""Trains a predictor with just text-specific parameters"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(
kh.get_samples_dir(), "NegativeAirlineTweets", "NegativeAirlineTweets.kdic"
)
data_table_path = os.path.join(
kh.get_samples_dir(), "NegativeAirlineTweets", "NegativeAirlineTweets.txt"
)
report_file_path = os.path.join(
"kh_samples", "train_predictor_text", "AnalysisResults.khj"
)
# Train the predictor
kh.train_predictor(
dictionary_file_path,
"FlightNegativeTweets",
data_table_path,
"negativereason",
report_file_path,
max_trees=5,
max_text_features=1000,
text_features="words",
)
def train_predictor_error_handling():
"""Shows how to handle errors when training a predictor
Trains the predictor and handles the errors by printing a custom message. When the
Khiops application fails the Khiops Python library will raise a
KhiopsRuntimeError reporting the errors encountered by Khiops.
If the latter information is not enough to diagnose the problem, it is possible to
save the temporary log file by activating the "trace" flag in the call to
`~.api.train_predictor`. The path of the log file will be printed to the standard
output, as well as that of the dictionary and scenario files (note that the "trace"
keyword argument is available in all functions of the `khiops.core.api`
submodule).
"""
# Imports
import os
from khiops import core as kh
# Set the file paths with a nonexistent dictionary file
dictionary_file_path = "NONEXISTENT_DICTIONARY_FILE.kdic"
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "train_predictor_error_handling")
report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
log_file_path = os.path.join(output_dir, "khiops.log")
scenario_path = os.path.join(output_dir, "scenario._kh")
# Train the predictor and handle the error
try:
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
trace=True,
log_file_path=log_file_path,
output_scenario_path=scenario_path,
)
except kh.KhiopsRuntimeError as error:
print("Khiops training failed! Below the KhiopsRuntimeError message:")
print(error)
print("\nFull log contents:")
print("------------------")
with open(log_file_path) as log_file:
for line in log_file:
print(line, end="")
print("\nExecuted scenario")
print("-----------------")
with open(scenario_path) as scenario_file:
for line in scenario_file:
print(line, end="")
def train_predictor_mt():
"""Trains a multi-table predictor in the simplest way possible
It is a call to `~.api.train_predictor` with additional parameters to handle
multi-table learning
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
accidents_dir = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
dictionary_file_path = os.path.join(accidents_dir, "Accidents.kdic")
accidents_table_path = os.path.join(accidents_dir, "Accidents.txt")
vehicles_table_path = os.path.join(accidents_dir, "Vehicles.txt")
report_file_path = os.path.join(
"kh_samples", "train_predictor_mt", "AnalysisResults.khj"
)
# Train the predictor. Besides the mandatory parameters, we specify:
# - A python dictionary linking data paths to file paths for non-root tables
# - To not construct any decision tree
# The default number of automatic features is 100
kh.train_predictor(
dictionary_file_path,
"Accident",
accidents_table_path,
"Gravity",
report_file_path,
additional_data_tables={"Vehicles": vehicles_table_path},
max_trees=0,
)
def train_predictor_mt_with_specific_rules():
"""Trains a multi-table predictor with specific construction rules
It is the same as `.train_predictor_mt` but with the specification of the allowed
variable construction rules. The list of available rules is found in the field
``kh.all_construction_rules``
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
accidents_dir = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
dictionary_file_path = os.path.join(accidents_dir, "Accidents.kdic")
accidents_table_path = os.path.join(accidents_dir, "Accidents.txt")
vehicles_table_path = os.path.join(accidents_dir, "Vehicles.txt")
report_file_path = os.path.join(
"kh_samples",
"train_predictor_mt_with_specific_rules",
"AnalysisResults.khj",
)
# Train the predictor. Besides the mandatory parameters, it is specified:
# - A python dictionary linking data paths to file paths for non-root tables
# - The maximum number of aggregate variables to construct (1000)
# - The construction rules allowed to automatically create aggregates
# - To not construct any decision tree
kh.train_predictor(
dictionary_file_path,
"Accident",
accidents_table_path,
"Gravity",
report_file_path,
additional_data_tables={"Vehicles": vehicles_table_path},
max_constructed_variables=1000,
construction_rules=["TableMode", "TableSelection"],
max_trees=0,
)
def train_predictor_mt_snowflake():
"""Trains a multi-table predictor for a dataset with a snowflake schema"""
# Imports
import os
from khiops import core as kh
# Set the file paths
accidents_dir = os.path.join(kh.get_samples_dir(), "Accidents")
dictionary_file_path = os.path.join(accidents_dir, "Accidents.kdic")
accidents_table_path = os.path.join(accidents_dir, "Accidents.txt")
vehicles_table_path = os.path.join(accidents_dir, "Vehicles.txt")
users_table_path = os.path.join(accidents_dir, "Users.txt")
places_table_path = os.path.join(accidents_dir, "Places.txt")
report_file_path = os.path.join(
"kh_samples", "train_predictor_mt_snowflake", "AnalysisResults.khj"
)
# Train the predictor. Besides the mandatory parameters, we specify:
# - A python dictionary linking data paths to file paths for non-root tables
# - To not construct any decision tree
# The default number of automatic features is 100
kh.train_predictor(
dictionary_file_path,
"Accident",
accidents_table_path,
"Gravity",
report_file_path,
additional_data_tables={
"Vehicles": vehicles_table_path,
"Vehicles/Users": users_table_path,
"Place": places_table_path,
},
max_trees=0,
)
def train_predictor_with_train_percentage():
"""Trains a predictor with a 90%-10% train-test split
Note: The default is a 70%-30% split
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples",
"train_predictor_with_train_percentage",
"P90_AnalysisResults.khj",
)
# Train the predictor. Besides the mandatory parameters, it is specified:
# - A 90% sampling rate for the training dataset
# - Set the test dataset as the complement of the training dataset (10%)
# - No trees
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
sample_percentage=90,
use_complement_as_test=True,
max_trees=0,
)
def train_predictor_with_trees():
"""Trains a predictor based on 15 trees with a 80%-20% train-test split"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Letter", "Letter.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Letter", "Letter.txt")
report_file_path = os.path.join(
"kh_samples", "train_predictor_with_trees", "P80_AnalysisResults.khj"
)
# Train the predictor with at most 15 trees (default 10)
kh.train_predictor(
dictionary_file_path,
"Letter",
data_table_path,
"lettr",
report_file_path,
sample_percentage=80,
use_complement_as_test=True,
max_trees=15,
)
def train_predictor_with_pairs():
"""Trains a predictor with user specified pairs of variables"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples", "train_predictor_with_pairs", "AnalysisResults.khj"
)
# Train the predictor with at most 10 pairs as follows:
# - Include pairs age-race and capital_gain-capital_loss
# - Include all possible pairs having relationship as component
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
use_complement_as_test=True,
max_trees=0,
max_pairs=10,
specific_pairs=[
("age", "race"),
("capital_gain", "capital_loss"),
("relationship", ""),
],
)
def train_predictor_with_multiple_parameters():
"""Trains a predictor with various additional parameters
Some of these parameters are specific to `~.api.train_predictor` and others generic
to any Khiops execution.
In this example, we specify the following parameters in the call:
- A main target value
- The path where to store the "Khiops scenario" script
- The path where to store the log of the process
- The flag to show the execution trace (generic to any `khiops.core.api`
function)
Additionally the Khiops runner is set such that the learning is executed with only
1000 MB of memory.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "train_predictor_with_multiple_parameters")
report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
output_script_path = os.path.join(output_dir, "output_scenario._kh")
log_path = os.path.join(output_dir, "log.txt")
# Train the predictor. Besides the mandatory parameters, we specify:
# - The value "more" as main target value
# - The output Khiops script file location (generic)
# - The log file location (generic)
# - The maximum memory used, set to 1000 MB
# - To show the debug trace (generic)
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
main_target_value="more",
output_scenario_path=output_script_path,
log_file_path=log_path,
memory_limit_mb=1000,
trace=True,
)
def train_predictor_detect_format():
"""Trains a predictor without specifying the table format"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Iris", "Iris.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Iris", "Iris.txt")
output_dir = os.path.join("kh_samples", "train_predictor_detect_format")
transformed_data_table_path = os.path.join(output_dir, "TransformedIris.txt")
report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
# Transform the database format from header_line=True and field_separator=TAB
# to header_line=False and field_separator=","
# See the deploy_model examples below for more details
kh.deploy_model(
dictionary_file_path,
"Iris",
data_table_path,
transformed_data_table_path,
output_header_line=False,
output_field_separator=",",
)
# Try to learn with the old format
try:
kh.train_predictor(
dictionary_file_path,
"Iris",
transformed_data_table_path,
"Class",
report_file_path,
header_line=True,
field_separator="",
)
except kh.KhiopsRuntimeError as error:
print(
"This failed because of a bad data table format spec. "
+ "Below the KhiopsRuntimeError message"
)
print(error)
# Train without specifyng the format (detect_format is True by default)
kh.train_predictor(
dictionary_file_path,
"Iris",
transformed_data_table_path,
"Class",
report_file_path,
)
def train_predictor_with_cross_validation():
"""Trains a predictor with a 5-fold cross-validation"""
# Imports
import math
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "train_predictor_with_cross_validation")
fold_dictionary_file_path = os.path.join(output_dir, "AdultWithFolding.kdic")
# Create the output directory
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
# Load the learning dictionary object
domain = kh.read_dictionary_file(dictionary_file_path)
dictionary = domain.get_dictionary("Adult")
# Add a random fold index variable to the learning dictionary
fold_number = 5
fold_index_variable = kh.Variable()
fold_index_variable.name = "FoldIndex"
fold_index_variable.type = "Numerical"
fold_index_variable.used = False
fold_index_variable.rule = "Ceil(Product(" + str(fold_number) + ", Random()))"
dictionary.add_variable(fold_index_variable)
# Add variables that indicate if the instance is in the train dataset:
for fold_index in range(1, fold_number + 1):
is_in_train_dataset_variable = kh.Variable()
is_in_train_dataset_variable.name = "IsInTrainDataset" + str(fold_index)
is_in_train_dataset_variable.type = "Numerical"
is_in_train_dataset_variable.used = False
is_in_train_dataset_variable.rule = "NEQ(FoldIndex, " + str(fold_index) + ")"
dictionary.add_variable(is_in_train_dataset_variable)
# Print dictionary with fold variables
print("Dictionary file with fold variables")
domain.export_khiops_dictionary_file(fold_dictionary_file_path)
with open(fold_dictionary_file_path) as fold_dictionary_file:
for line in fold_dictionary_file:
print(line, end="")
# For each fold k:
print("Training Adult with " + str(fold_number) + " folds")
print("\tfold\ttrain auc\ttest auc")
train_aucs = []
test_aucs = []
for fold_index in range(1, fold_number + 1):
analysis_report_file_path = os.path.join(
output_dir, "Fold" + str(fold_index) + "AnalysisResults.khj"
)
# Train a model from the sub-dataset where IsInTrainDataset<k> is 1
_, modeling_dictionary_file_path = kh.train_predictor(
domain,
"Adult",
data_table_path,
"class",
analysis_report_file_path,
sample_percentage=100,
selection_variable="IsInTrainDataset" + str(fold_index),
selection_value=1,
max_trees=0,
)
evaluation_report_file_path = os.path.join(
output_dir, "Fold" + str(fold_index) + "AdultEvaluationResults.khj"
)
# Evaluate the resulting model in the subsets where IsInTrainDataset is 0
test_evaluation_report_path = kh.evaluate_predictor(
modeling_dictionary_file_path,
"SNB_Adult",
data_table_path,
evaluation_report_file_path,
sample_percentage=100,
selection_variable="IsInTrainDataset" + str(fold_index),
selection_value=0,
)
# Obtain the train AUC from the train report and the test AUC from the
# evaluation report and print them
train_results = kh.read_analysis_results_file(analysis_report_file_path)
test_evaluation_results = kh.read_analysis_results_file(
test_evaluation_report_path
)
train_auc = train_results.train_evaluation_report.get_snb_performance().auc
test_auc = test_evaluation_results.evaluation_report.get_snb_performance().auc
print("\t" + str(fold_index) + "\t" + str(train_auc) + "\t" + str(test_auc))
# Store the train and test AUCs in arrays
train_aucs.append(train_auc)
test_aucs.append(test_auc)
# Print the mean +- error aucs for both train and test
mean_train_auc = sum(train_aucs) / fold_number
squared_error_train_aucs = [(auc - mean_train_auc) ** 2 for auc in train_aucs]
sd_train_auc = math.sqrt(sum(squared_error_train_aucs) / (fold_number - 1))
mean_test_auc = sum(test_aucs) / fold_number
squared_error_test_aucs = [(auc - mean_test_auc) ** 2 for auc in test_aucs]
sd_test_auc = math.sqrt(sum(squared_error_test_aucs) / (fold_number - 1))
print("final auc")
print("train auc: " + str(mean_train_auc) + " +- " + str(sd_train_auc))
print("test auc: " + str(mean_test_auc) + " +- " + str(sd_test_auc))
def multiple_train_predictor():
"""Trains a sequence of models with a decreasing number of variables
This example illustrates the use of the khiops classes `.DictionaryDomain` (for
reading dictionary files) and `.AnalysisResults` (for reading training/evaluation
results from JSON)
"""
# Imports
import os
from khiops import core as kh
def display_test_results(json_result_file_path):
"""Display some of the training results"""
results = kh.read_analysis_results_file(json_result_file_path)
train_performance = results.train_evaluation_report.get_snb_performance()
test_performance = results.test_evaluation_report.get_snb_performance()
print(
"\t"
+ str(len(results.preparation_report.variables_statistics))
+ "\t"
+ str(train_performance.auc)
+ "\t"
+ str(test_performance.auc)
)
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "multiple_train_predictor")
report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
# Read the dictionary file to obtain an instance of class Dictionary
dictionary_domain = kh.read_dictionary_file(dictionary_file_path)
dictionary = dictionary_domain.get_dictionary("Adult")
# Train a SNB model using all the variables
print("\t#vars\ttrain auc\ttest auc")
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
sample_percentage=70,
use_complement_as_test=True,
max_trees=0,
)
display_test_results(report_file_path)
# Read results to obtain the variables sorted by decreasing Level
analysis_results = kh.read_analysis_results_file(report_file_path)
preparation_results = analysis_results.preparation_report
# Train a sequence of models with a decreasing number of variables
# We disable variables one-by-one in increasing level (predictive power) order
variable_number = len(preparation_results.variables_statistics)
for i in reversed(range(variable_number)):
# Search the next variable
variable = preparation_results.variables_statistics[i]
# Disable this variable and save the dictionary with the Khiops format
dictionary.get_variable(variable.name).used = False
# Train the model with this dictionary domain object
report_file_path = os.path.join(
output_dir, f"V{variable_number - 1 - i}_AnalysisResults.khj"
)
kh.train_predictor(
dictionary_domain,
"Adult",
data_table_path,
"class",
report_file_path,
sample_percentage=70,
use_complement_as_test=True,
max_trees=0,
)
# Show a preview of the results
display_test_results(report_file_path)
def interpret_predictor():
"""Builds interpretation model for existing predictor
It calls `~.api.train_predictor` and `~.api.interpret_predictor` only with
their mandatory parameters.
"""
# Imports
import os
from khiops import core as kh
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "interpret_predictor")
analysis_report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
interpretor_file_path = os.path.join(output_dir, "InterpretationModel.kdic")
# Build prediction model
_, predictor_file_path = kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
analysis_report_file_path,
)
# Build interpretation model
kh.interpret_predictor(predictor_file_path, "SNB_Adult", interpretor_file_path)
print(f"The interpretation model is '{interpretor_file_path}'")
def evaluate_predictor():
"""Evaluates a predictor in the simplest way possible
It calls `~.api.evaluate_predictor` with only its mandatory parameters.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
output_dir = os.path.join("kh_samples", "evaluate_predictor")
analysis_report_file_path = os.path.join(output_dir, "AnalysisResults.khj")
# Train the predictor
_, model_dictionary_file_path = kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
analysis_report_file_path,
max_trees=0,
)
evaluation_report_file_path = os.path.join(output_dir, "AdultEvaluationResults.khj")
# Evaluate the predictor
kh.evaluate_predictor(
model_dictionary_file_path,
"SNB_Adult",
data_table_path,
evaluation_report_file_path,
)
print("Evaluation report available at " + evaluation_report_file_path)
def access_predictor_evaluation_report():
"""Shows the performance metrics of a predictor
See `evaluate_predictor` or `train_predictor_with_train_percentage` to see examples
on how to evaluate a model.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples", "access_predictor_evaluation_report", "AdultAnalysisReport.khj"
)
# Train the SNB predictor and some univariate predictors
# Note: Evaluation in test is 30% by default
kh.train_predictor(
dictionary_file_path,
"Adult",
data_table_path,
"class",
report_file_path,
max_trees=0,
)
# Obtain the evaluation results
results = kh.read_analysis_results_file(report_file_path)
evaluation_report = results.test_evaluation_report
snb_performance = evaluation_report.get_snb_performance()
# Print univariate metrics for the SNB
print("\nperformance metrics for " + snb_performance.name)
for metric_name in snb_performance.get_metric_names():
print(metric_name + ": " + str(snb_performance.get_metric(metric_name)))
# Print the confusion matrix
print("\nconfusion matrix:")
confusion_matrix = snb_performance.confusion_matrix
for target_value in confusion_matrix.values:
print("\t" + target_value, end="")
print("")
for i, target_value in enumerate(confusion_matrix.values):
observed_frequencies = confusion_matrix.matrix[i]
print(target_value, end="")
for frequency in observed_frequencies:
print("\t" + str(frequency), end="")
print("")
# Print the head of the lift curves for the 'more' modality
print("\nfirst five values of the lift curves for 'more'")
snb_lift_curve = evaluation_report.get_snb_lift_curve("more")
optimal_lift_curve = evaluation_report.get_classifier_lift_curve("Optimal", "more")
random_lift_curve = evaluation_report.get_classifier_lift_curve("Random", "more")
for i in range(5):
print(
str(snb_lift_curve.values[i])
+ "\t"
+ str(optimal_lift_curve.values[i])
+ "\t"
+ str(random_lift_curve.values[i])
)
# Print metrics for an SNB predictor
predictor_performance = evaluation_report.get_predictor_performance(
"Selective Naive Bayes"
)
print("\n\nperformance metrics for " + predictor_performance.name)
for metric_name in predictor_performance.get_metric_names():
print(metric_name + ": " + str(predictor_performance.get_metric(metric_name)))
def train_recoder():
"""Train a database recoder in the simplest way possible
It is a call to `~.api.train_recoder` with only its mandatory parameters.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples", "train_recoder", "AnalysisResults.khj"
)
# Train the recoder model
kh.train_recoder(
dictionary_file_path, "Adult", data_table_path, "class", report_file_path
)
def train_recoder_with_multiple_parameters():
"""Trains a recoder that transforms variable values to their respective part labels
It also creates 10 pair features.
"""
# Imports
import os
from khiops import core as kh
# Set the file paths
dictionary_file_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.kdic")
data_table_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
report_file_path = os.path.join(
"kh_samples",
"train_recoder_with_multiple_parameters",
"AnalysisResults.khj",