-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
2199 lines (1974 loc) · 80.3 KB
/
Copy pathapi.py
File metadata and controls
2199 lines (1974 loc) · 80.3 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. #
######################################################################################
"""API for the execution of the Khiops AutoML suite
The methods in this module allow to execute all Khiops and Khiops Coclustering tasks.
See also:
- :ref:`core-api-common-params`
- :ref:`core-api-input-types`
- :ref:`core-api-sampling-mode`
- :ref:`core-api-env-samples-dir`
"""
import io
import os
import warnings
import khiops.core.internals.filesystems as fs
from khiops.core.dictionary import DictionaryDomain
from khiops.core.exceptions import KhiopsRuntimeError
from khiops.core.internals.common import (
CommandLineOptions,
SystemSettings,
deprecation_message,
is_string_like,
type_error_message,
)
from khiops.core.internals.runner import get_runner
from khiops.core.internals.task import get_task_registry
# Construction rules
DEFAULT_CONSTRUCTION_RULES = [
"GetValue",
"GetValueC",
"TableCount",
"TableCountDistinct",
"TableMax",
"TableMean",
"TableMedian",
"TableMin",
"TableMode",
"TableSelection",
"TableStdDev",
"TableSum",
]
"""List of construction rules that Khiops uses by default
.. note::
These are all the multi-table rules.
""" # pylint: disable=pointless-string-statement
CALENDRICAL_CONSTRUCTION_RULES = [
"Day",
"DecimalTime",
"DecimalWeekDay",
"DecimalYear",
"DecimalYearTS",
"GetDate",
"GetTime",
"LocalTimestamp",
"WeekDay",
"YearDay",
]
"""List of calendrical construction rules
These rules include: date, time and timestamp rules.
.. note::
These rules are not enabled by default. The user needs to explicitly
select each of them via the ``construction_rules`` parameter of the
relevant Core API functions.
""" # pylint: disable=pointless-string-statement
# List of all available construction rules in the Khiops tool
ALL_CONSTRUCTION_RULES = DEFAULT_CONSTRUCTION_RULES + CALENDRICAL_CONSTRUCTION_RULES
##########################
# Private module methods #
##########################
def _check_dictionary_file_path_or_domain(dictionary_file_path_or_domain):
"""Checks if the argument is a string or DictionaryDomain or raise TypeError"""
if not is_string_like(dictionary_file_path_or_domain) and not isinstance(
dictionary_file_path_or_domain, DictionaryDomain
):
raise TypeError(
type_error_message(
"dictionary_file_path_or_domain",
dictionary_file_path_or_domain,
str,
DictionaryDomain,
)
)
def _get_or_create_execution_dictionary_file(dictionary_file_path_or_domain, trace):
"""Access the dictionary path or creates one from a DictionaryDomain object"""
# Check the type of dictionary_file_path_or_domain
_check_dictionary_file_path_or_domain(dictionary_file_path_or_domain)
# If the argument is a DictionaryDomain export it to a temporary file
if isinstance(dictionary_file_path_or_domain, DictionaryDomain):
execution_dictionary_file_path = get_runner().create_temp_file(
"_dictionary_", ".kdic"
)
dictionary_file_path_or_domain.export_khiops_dictionary_file(
execution_dictionary_file_path
)
if trace:
print(f"Khiops execution dictionary file: {execution_dictionary_file_path}")
else:
execution_dictionary_file_path = dictionary_file_path_or_domain
return execution_dictionary_file_path
def _run_task(task_name, task_args):
"""Generic task run method
Parameters
----------
task_name : str
Name of the task.
task_args : dict
Arguments of the task.
"""
# Save the `runner.run` arguments other than the task parameters and options
trace = task_args["trace"]
stdout_file_path = task_args["stdout_file_path"]
stderr_file_path = task_args["stderr_file_path"]
command_line_options, system_settings, task_called_with_domain = (
_preprocess_arguments(task_args)
)
# Obtain the api function from the registry
task = get_task_registry().get_task(task_name, get_khiops_version())
# Execute the Khiops task and cleanup when necessary
try:
get_runner().run(
task,
task_args,
command_line_options=command_line_options,
trace=trace,
system_settings=system_settings,
stdout_file_path=stdout_file_path,
stderr_file_path=stderr_file_path,
)
finally:
if task_called_with_domain and not trace:
fs.remove(task_args["dictionary_file_path"])
def _preprocess_arguments(args):
"""Preprocessing of Khiops arguments
Parameters
----------
args : dict
The Khiops arguments.
Returns
-------
tuple
A 3-tuple containing:
- A `~.CommandLineOptions` instance
- A `~.SystemSettings` instance
- A `bool` that is ``True`` if the value of the `dictionary_file_or_domain`
`args` key is a `~.DictionaryDomain` instance.
.. note:: This function *mutates* the input `args` dictionary.
"""
# Execute the preprocess of common task arguments
task_is_called_with_domain = _preprocess_task_arguments(args)
# Create a command line options object
command_line_options = CommandLineOptions(
log_file_path=(args["log_file_path"] if "log_file_path" in args else ""),
output_scenario_path=(
args["output_scenario_path"] if "output_scenario_path" in args else ""
),
task_file_path=(args["task_file_path"] if "task_file_path" in args else ""),
)
# Create a system settings object
system_settings = SystemSettings()
for arg in args:
if arg == "max_cores":
max_cores = args[arg]
if max_cores is not None:
system_settings.max_cores = int(max_cores)
elif arg == "memory_limit_mb":
memory_limit_mb = args[arg]
if memory_limit_mb is not None:
system_settings.memory_limit_mb = int(memory_limit_mb)
elif arg == "temp_dir":
temp_dir = args[arg]
# temp_dir is set to a non-empty string
if temp_dir:
system_settings.temp_dir = temp_dir
elif arg == "scenario_prologue":
scenario_prologue = args[arg]
# User-defined scenario prologue is set to a non-empty string
if scenario_prologue:
system_settings.scenario_prologue = scenario_prologue
system_settings.check()
# Clean the args to leave only the task arguments
_clean_task_args(args)
return command_line_options, system_settings, task_is_called_with_domain
def _deprecate_legacy_data_path(data_path_task_arg_name, task_args):
"""Detect and replace legacy data path with the current syntax
.. note:: The function mutates task_args.
"""
if (
data_path_task_arg_name in task_args
and task_args[data_path_task_arg_name] is not None
):
assert "dictionary_name" in task_args or "train_dictionary_name" in task_args
if "dictionary_name" in task_args:
current_dictionary_name = task_args["dictionary_name"]
else:
current_dictionary_name = task_args["train_dictionary_name"]
for kdic_path in task_args[data_path_task_arg_name].keys():
if isinstance(kdic_path, str):
deprecated_data_path_separator = "`"
data_path_separator = "/"
kdic_path_for_warning = kdic_path
else:
assert isinstance(kdic_path, bytes)
deprecated_data_path_separator = b"`"
data_path_separator = b"/"
if isinstance(current_dictionary_name, str):
current_dictionary_name = bytes(
current_dictionary_name, encoding="ascii"
)
kdic_path_for_warning = kdic_path.decode("ascii")
# Path split "`" yields non-empty fragments; the first fragment
# starts with the current dictionary name
kdic_path_parts = kdic_path.split(deprecated_data_path_separator)
if all(len(path_part) > 0 for path_part in kdic_path_parts):
source_dictionary_name = kdic_path_parts[0]
if source_dictionary_name == current_dictionary_name:
# Escape any "/" char in the path parts except for the
# current dictionary, which is is skipped from the new path
new_kdic_path_parts = []
for kdic_path_part in kdic_path_parts[1:]:
new_kdic_path_parts.append(
kdic_path_part.replace(
data_path_separator,
deprecated_data_path_separator + data_path_separator,
)
)
# Replace the legacy data path with the current data path
new_kdic_path = data_path_separator.join(new_kdic_path_parts)
kdic_file_path = task_args[data_path_task_arg_name].pop(kdic_path)
task_args[data_path_task_arg_name][new_kdic_path] = kdic_file_path
warnings.warn(
deprecation_message(
"'`'-based dictionary data path: "
f"'{kdic_path_for_warning}'",
"11.0.1",
replacement=(
"'/'-based dictionary data path "
f"convention: '{new_kdic_path}'"
),
quote=False,
)
)
def _preprocess_task_arguments(task_args):
"""Preprocessing of task arguments common to various tasks
Parameters
----------
task_args : dict
The task arguments.
Returns
-------
bool
``True`` if the task was called with an input `.DictionaryDomain`.
"""
# Process the output path
# if path is dir, then generate full report path according to GUI defaults
file_path_arg_names = {
"analysis_report_file_path": "AnalysisResults.khj",
"evaluation_report_file_path": "EvaluationReport.khj",
"coclustering_report_file_path": "Coclustering.khcj",
"coclustering_dictionary_file_path": "Coclustering.kdic",
}
for file_path_arg_name, default_file_name in file_path_arg_names.items():
if file_path_arg_name in task_args:
file_path = task_args[file_path_arg_name]
# If path ends with path separator or exists as a dir, then consider
# it is dir and concatenate default report file name to it
if file_path.endswith(os.path.sep) or (
fs.is_local_resource(file_path) and os.path.isdir(file_path)
):
# Add deprecation warning
warnings.warn(
deprecation_message(
"'results_dir'",
"11.0.1",
replacement=file_path_arg_name,
quote=False,
)
)
# Update the path
if fs.is_local_resource(file_path):
norm_file_path = os.path.normpath(file_path)
else:
norm_file_path = file_path
full_file_path = fs.get_child_path(norm_file_path, default_file_name)
task_args[file_path_arg_name] = full_file_path
# Process the input dictionary domain if any
# build_frequency_variables and detect_format are processed differently below
task_called_with_domain = False
if "dictionary_file_path_or_domain" in task_args:
task_called_with_domain = isinstance(
task_args["dictionary_file_path_or_domain"], DictionaryDomain
)
task_args["dictionary_file_path"] = _get_or_create_execution_dictionary_file(
task_args["dictionary_file_path_or_domain"], task_args["trace"]
)
# Transform the use_complement_as_test bool parameter to its string counterpart
if "use_complement_as_test" in task_args:
if task_args["use_complement_as_test"]:
task_args["test_database_mode"] = "Complementary"
else:
task_args["test_database_mode"] = "None"
del task_args["use_complement_as_test"]
# Preprocess the database format parameters
if "detect_format" in task_args:
assert "header_line" in task_args
assert "field_separator" in task_args
detect_format, header_line, field_separator = _preprocess_format_spec(
task_args["detect_format"],
task_args["header_line"],
task_args["field_separator"],
)
task_args["detect_format"] = detect_format
task_args["header_line"] = header_line
task_args["field_separator"] = field_separator
if "output_header_line" in task_args:
assert "output_field_separator" in task_args
_, header_line, field_separator = _preprocess_format_spec(
False, task_args["output_header_line"], task_args["output_field_separator"]
)
task_args["output_header_line"] = header_line
task_args["output_field_separator"] = field_separator
# Preprocess the selection_value parameter
if "selection_value" in task_args:
if isinstance(task_args["selection_value"], (int, float)):
task_args["selection_value"] = str(task_args["selection_value"])
# Detect and replace deprecated data-path syntax on additional_data_tables
# Mutate task_args in the process
for data_path_task_arg_name in (
"additional_data_tables",
"output_additional_data_tables",
):
_deprecate_legacy_data_path(data_path_task_arg_name, task_args)
# Flatten kwargs
if "kwargs" in task_args:
task_args.update(task_args["kwargs"])
del task_args["kwargs"]
return task_called_with_domain
def _preprocess_format_spec(detect_format, header_line, field_separator):
r"""Preprocess the user format spec to be used in a task
More precisely:
- Sets ``detect_format`` to ``False`` if either ``header_line`` or
``field_separator`` are set
- If either ``header_line`` or ``field_separator`` is ``None``, then they are
set to their default values
- It transforms the field separator "\\t" to the empty string ""
"""
# Ignore detect_format if header_line or field_separator are set
if header_line is not None or field_separator is not None:
detect_format = False
# Set the default values of header_line and field_separator
if header_line is None:
header_line = True
if field_separator is None:
field_separator = ""
# Fail on separators with more than one char
if len(field_separator) > 1:
raise ValueError("'field_separator' must have length at most 1")
# Transform tab field_separator to empty string
if field_separator == "\t":
field_separator = ""
return detect_format, header_line, field_separator
def _clean_task_args(task_args):
"""Cleans the task arguments
More precisely it removes:
- Command line arguments (they already are in another object).
- System settings (they already are in another object).
- Parameters removed from the API and warns about it.
- Renamed API parameters and warns about it.
"""
# Remove non-task parameters
command_line_arg_names = [
"log_file_path",
"output_scenario_path",
"task_file_path",
]
system_settings_arg_names = [
"max_cores",
"memory_limit_mb",
"temp_dir",
"scenario_prologue",
]
other_arg_names = [
"dictionary_file_path_or_domain",
"trace",
"stdout_file_path",
"stderr_file_path",
]
for arg_name in (
command_line_arg_names + system_settings_arg_names + other_arg_names
):
if arg_name in task_args:
del task_args[arg_name]
#########
# Tasks #
#########
# WARNING: All API methods that use task objects have the following first instruction:
#
# task_args = locals()
#
# This line must not be moved from there because the return value of locals() depends on
# the state of the program. When it is called as the first instruction of a function it
# contains only the values of its parameters.
def get_khiops_version():
"""Returns the Khiops version
Returns
-------
str
The Khiops version of the current `.KhiopsRunner` backend.
"""
return get_runner().khiops_version
def get_samples_dir():
"""Returns the Khiops' *samples* directory path
Returns
-------
str
The path of the Khiops *samples* directory.
"""
return get_runner().samples_dir
# Disable the unused arg rule because we use locals() to pass the arguments to _run_task
# pylint: disable=unused-argument
def export_dictionary_as_json(
dictionary_file_path_or_domain,
json_dictionary_file_path,
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
):
"""Exports a Khiops dictionary file to JSON format (``.kdicj``)
Parameters
----------
dictionary_file_path_or_domain : str or `.DictionaryDomain`
Path of a Khiops dictionary file or a DictionaryDomain object.
json_dictionary_file_path : str
Path (absolute path recommended) to the output dictionary file,
in the JSON format. Note that a relative path will produce a file in
the current working directory.
... :
See :ref:`core-api-common-params`.
Examples
--------
See the following function of the ``samples.py`` documentation script:
- `samples.export_dictionary_files()`
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the task
_run_task("export_dictionary_as_json", task_args)
def build_dictionary_from_data_table(
data_table_path,
output_dictionary_name,
output_dictionary_file_path,
detect_format=True,
header_line=None,
field_separator=None,
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
**kwargs,
):
r"""Builds a dictionary file by analyzing a data table file
Parameters
----------
data_table_path : str
Path of the data table file.
output_dictionary_name : str
Name dictionary to be created.
output_dictionary_file_path : str
Path (absolute path recommended) of the output dictionary file. Note that
a relative path will produce a file in the current working directory.
detect_format : bool, default ``True``
If ``True`` detects automatically whether the data table file has a header and
its field separator. It is set to ``False`` if ``header_line`` or
``field_separator`` are set.
header_line : bool, optional (default ``True``)
If ``True`` it uses the first line of the data as column names. Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
field_separator : str, optional (default "\\t")
A field separator character. "" has the same effect as "\\t". Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
... :
See :ref:`core-api-common-params`.
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the ttask
_run_task("build_dictionary_from_data_table", task_args)
def check_database(
dictionary_file_path_or_domain,
dictionary_name,
data_table_path,
detect_format=True,
header_line=None,
field_separator=None,
sample_percentage=100.0,
sampling_mode="Include sample",
selection_variable="",
selection_value="",
additional_data_tables=None,
max_messages=20,
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
**kwargs,
):
r"""Checks if a data table is compatible with a dictionary file
Parameters
----------
dictionary_file_path_or_domain : str or `.DictionaryDomain`
Path of a Khiops dictionary file or a DictionaryDomain object.
dictionary_name : str
Name of the dictionary of the table to be checked.
data_table_path : str
Path of the data table file.
detect_format : bool, default ``True``
If ``True`` detects automatically whether the data table file has a header and
its field separator. It is set to ``False`` if ``header_line`` or
``field_separator`` are set.
header_line : bool, optional (default ``True``)
If ``True`` it uses the first line of the data as column names. Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
field_separator : str, optional (default "\\t")
A field separator character. "" has the same effect as "\\t". Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
sample_percentage : float, default 100.0
See the ``sampling_mode`` option below.
sampling_mode : "Include sample" or "Exclude sample"
If equal to "Include sample" it checks ``sample_percentage`` percent of
the data; if equal to "Exclude sample" it checks the complement of the
data selected with "Include sample". See also :ref:`core-api-sampling-mode`.
selection_variable : str, default ""
It checks only the records such that the value of ``selection_variable`` is
equal to ``selection_value``. Ignored if equal to "".
selection_value: str or int or float, default ""
See ``selection_variable`` option above. Ignored if equal to "".
additional_data_tables : dict, optional
A dictionary containing the data paths and file paths for a multi-table
dictionary file. For more details see :doc:`/multi_table_primer`.
max_messages : int, default 20
Maximum number of error messages to write in the log file.
... :
See :ref:`core-api-common-params`.
Examples
--------
See the following function of the ``samples.py`` documentation script:
- `samples.check_database()`
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the task
_run_task("check_database", task_args)
def train_predictor(
dictionary_file_path_or_domain,
dictionary_name,
data_table_path,
target_variable,
analysis_report_file_path,
detect_format=True,
header_line=None,
field_separator=None,
sample_percentage=70.0,
sampling_mode="Include sample",
use_complement_as_test=True,
selection_variable="",
selection_value="",
additional_data_tables=None,
do_data_preparation_only=False,
main_target_value="",
keep_selected_variables_only=True,
max_evaluated_variables=0,
max_selected_variables=0,
max_constructed_variables=1000,
construction_rules=None,
max_text_features=10000,
text_features="words",
max_trees=10,
max_pairs=0,
all_possible_pairs=True,
specific_pairs=None,
group_target_value=False,
discretization_method="MODL",
grouping_method="MODL",
max_parts=0,
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
**kwargs,
):
r"""Trains a model from a data table
Parameters
----------
dictionary_file_path_or_domain : str or `.DictionaryDomain`
Path of a Khiops dictionary file or a DictionaryDomain object.
dictionary_name : str
Name of the dictionary to be analyzed.
data_table_path : str
Path of the data table file.
target_variable : str
Name of the target variable. If the specified variable is categorical it
constructs a classifier and if it is numerical a regressor. If equal to "" it
performs an unsupervised analysis.
analysis_report_file_path : str
Path (absolute path recommended) to the analysis report file,
in the JSON format. An additional dictionary file with the same name and
extension ``.model.kdic`` is built, which contains the trained models.
Note that a relative path will produce a report file in the current working
directory.
detect_format : bool, default ``True``
If ``True`` detects automatically whether the data table file has a header and
its field separator. It is set to ``False`` if ``header_line`` or
``field_separator`` are set.
header_line : bool, optional (default ``True``)
If ``True`` it uses the first line of the data as column names. Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
field_separator : str, optional (default "\\t")
A field separator character. "" has the same effect as "\\t". Sets
``detect_format`` to ``False`` if set. Ignored if ``detect_format``
is ``True``.
sample_percentage : float, default 70.0
See the ``sampling_mode`` option below.
sampling_mode : "Include sample" or "Exclude sample"
If equal to "Include sample" it trains the predictor on ``sample_percentage``
percent of the data and tests the model on the remainder of the data if
``use_complement_as_test`` is set to ``True``. If equal to "Exclude sample" the
train and test datasets above are exchanged. See also
:ref:`core-api-sampling-mode`.
use_complement_as_test : bool, default ``True``
Uses the complement of the sampled database as test database for
computing the model's performance metrics.
selection_variable : str, default ""
It trains with only the records such that the value of ``selection_variable`` is
equal to ``selection_value``. Ignored if equal to "".
selection_value: str or int or float, default ""
See ``selection_variable`` option above. Ignored if equal to "".
additional_data_tables : dict, optional
A dictionary containing the data paths and file paths for a multi-table
dictionary file. For more details see :doc:`/multi_table_primer`.
do_data_preparation_only : bool, default ``False``
If ``True`` it only does data preparation via MODL preprocessing without
training a Selective Naive Bayes Predictor.
main_target_value : str, default ""
If this target value is specified then it guarantees the calculation of lift
curves for it.
keep_selected_variables_only : bool, default ``True``
Keeps only predictor-selected variables in the supervised analysis report.
max_evaluated_variables : int, default 0
Maximum number of variables to be evaluated in the SNB predictor training. If
equal to 0 it evaluates all informative variables.
max_selected_variables : int, default 0
Maximum number of variables to be selected in the SNB predictor. If equal to
0 it selects all the variables kept in the training.
max_constructed_variables : int, default 1000
Maximum number of variables to construct.
construction_rules : list of str, optional
Allowed rules for the automatic variable construction. If not set, Khiops
uses the multi-table construction rules listed in
`DEFAULT_CONSTRUCTION_RULES`.
max_text_features : int, default 10000
Maximum number of text features to construct.
text_features : str, default "words"
Type of the text features. Can be either one of:
- "words": sequences of non-space characters
- "ngrams": sequences of bytes
- "tokens": user-defined
max_trees : int, default 10
Maximum number of trees to construct.
max_pairs : int, default 0
Maximum number of variable pairs to construct.
specific_pairs : list of tuple, optional
User-specified pairs as a list of 2-tuples of feature names. If a given tuple
contains only one non-empty feature name, then it generates all the pairs
containing it (within the maximum limit ``max_pairs``). These pairs have top
priority: they are constructed first.
all_possible_pairs : bool, default ``True``
If ``True`` tries to create all possible pairs within the limit ``max_pairs``.
Pairs specified with ``specific_pairs`` have top priority: they are constructed
first.
group_target_value : bool, default ``False``
Allows grouping of the target variable values in classification. It can
substantially increase the training time.
discretization_method : str, default "MODL"
Name of the discretization method in case of unsupervised analysis.
Its valid values are: "MODL", "EqualWidth", "EqualFrequency" or "none".
Ignored for supervised analysis.
grouping_method : str, default "MODL"
Name of the grouping method in case of unsupervised analysis.
Its valid values are: "MODL", "BasicGrouping" or "none".
Ignored for supervised analysis.
max_parts : int, default 0
Maximum number of variable parts produced by preprocessing methods. If equal
to 0 it is automatically calculated.
Special default values for unsupervised analysis:
- If ``discretization_method`` is "EqualWidth" or "EqualFrequency": 10
- If ``grouping_method`` is "BasicGrouping": 10
... :
See :ref:`core-api-common-params`.
Returns
-------
tuple
A 2-tuple containing:
- The reports file path
- The modeling dictionary file path in the supervised case.
Raises
------
`ValueError`
Invalid values of an argument
`TypeError`
Invalid type of an argument
Examples
--------
See the following functions of the ``samples.py`` documentation script:
- `samples.train_predictor()`
- `samples.train_predictor_file_paths()`
- `samples.train_predictor_error_handling()`
- `samples.train_predictor_mt()`
- `samples.train_predictor_mt_with_specific_rules()`
- `samples.train_predictor_with_train_percentage()`
- `samples.train_predictor_with_trees()`
- `samples.train_predictor_with_pairs()`
- `samples.train_predictor_with_multiple_parameters()`
- `samples.train_predictor_detect_format()`
- `samples.train_predictor_with_cross_validation()`
- `samples.multiple_train_predictor()`
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the task
_run_task("train_predictor", task_args)
# Return the paths of the JSON report and modelling dictionary file
if target_variable != "":
current_dir = fs.parent_path(analysis_report_file_path)
report_file_name, _ = os.path.splitext(
os.path.basename(analysis_report_file_path)
)
modeling_dictionary_file_path = fs.get_child_path(
current_dir, f"{report_file_name}.model.kdic"
)
else:
modeling_dictionary_file_path = None
return (analysis_report_file_path, modeling_dictionary_file_path)
def interpret_predictor(
dictionary_file_path_or_domain,
predictor_dictionary_name,
interpretor_file_path,
max_variable_importances=100,
importance_ranking="Global",
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
**kwargs,
):
r"""Builds an interpretation dictionary from a predictor
Parameters
----------
dictionary_file_path_or_domain : str or `.DictionaryDomain`
Path of a Khiops dictionary file or a DictionaryDomain object.
predictor_dictionary_name : str
Name of the predictor dictionary used while building the interpretation model.
interpretor_file_path : str
Path to the interpretor dictionary file.
max_variable_importances : int, default 100
Maximum number of variable importances to be selected in the interpretation
model. If the predictor contains fewer variables than this number, then
all the variables of the predictor are considered.
importance_ranking : str, default "Global"
Ranking of the Shapley values produced by the interpretor. Ca be one of:
- "Global": predictor variables are ranked by decreasing global importance.
- "Individual": predictor variables are ranked by decreasing individual
Shapley value.
... :
See :ref:`core-api-common-params`.
Raises
------
`ValueError`
Invalid values of an argument
`TypeError`
Invalid type of an argument
Examples
--------
See the following functions of the ``samples.py`` documentation script:
- `samples.interpret_predictor()`
- `samples.deploy_model_mt_with_interpretation()`
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the task
_run_task("interpret_predictor", task_args)
def reinforce_predictor(
dictionary_file_path_or_domain,
predictor_dictionary_name,
reinforced_predictor_file_path,
reinforcement_target_value="",
reinforcement_lever_variables=None,
log_file_path=None,
output_scenario_path=None,
task_file_path=None,
trace=False,
stdout_file_path="",
stderr_file_path="",
max_cores=None,
memory_limit_mb=None,
temp_dir="",
scenario_prologue="",
**kwargs,
):
r"""Builds a reinforced predictor from a predictor
A reinforced predictor is a model which increases the importance of specified lever
variables in order to increase the probability of occurrence of the specified target
value.
Parameters
----------
dictionary_file_path_or_domain : str or `.DictionaryDomain`
Path of a Khiops dictionary file or a DictionaryDomain object.
predictor_dictionary_name : str
Name of the predictor dictionary used while building the reinforced predictor.
reinforced_predictor_file_path : str
Path to the reinforced predictor dictionary file.
reinforcement_target_value : str, default ""
If this target value is specified, then its probability of occurrence is
tentatively increased.
reinforcement_lever_variables : list of str
The names of variables to use as lever variables while building the
reinforced predictor. Min length: 1. Max length: the total number of variables
in the prediction model.
... :
See :ref:`core-api-common-params`.
Raises
------
`ValueError`
Invalid values of an argument
`TypeError`
Invalid type of an argument
Examples
--------
See the following functions of the ``samples.py`` documentation script:
- `samples.reinforce_predictor()`
- `samples.deploy_reinforced_model_mt()`
"""
# Save the task arguments
# WARNING: Do not move this line, see the top of the "tasks" section for details
task_args = locals()
# Run the task