-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsamples_sklearn.py
More file actions
1013 lines (840 loc) · 34 KB
/
samples_sklearn.py
File metadata and controls
1013 lines (840 loc) · 34 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 sklearn submodule samples
The functions in this script demonstrate the basic use of the sklearn submodule of the
Khiops Python library.
"""
import argparse
import khiops
import os
from khiops import core as kh
# Disable PEP8 variable names because of scikit-learn X,y conventions
# To capture invalid-names other than X,y run:
# pylint --disable=all --enable=invalid-names samples_sklearn.py
# pylint: disable=invalid-name
# 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 khiops_classifier():
"""Trains a `.KhiopsClassifier` on a monotable dataframe"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Load the dataset into a pandas dataframe
adult_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
adult_df = pd.read_csv(adult_path, sep="\t")
# Split the whole dataframe into train and test (70%-30%)
adult_train_df, adult_test_df = train_test_split(
adult_df, test_size=0.3, random_state=1
)
# Split the dataset into:
# - the X feature table
# - the y target vector ("class" column)
X_train = adult_train_df.drop("class", axis=1)
X_test = adult_test_df.drop("class", axis=1)
y_train = adult_train_df["class"]
y_test = adult_test_df["class"]
# Create the classifier object
khc = KhiopsClassifier()
# Train the classifier
khc.fit(X_train, y_train)
# Show the feature importance info
print(f"Features evaluated: {khc.n_features_evaluated_}")
print(f"Features selected : {khc.n_features_used_}")
print("Top 3 used features")
for i, feature in enumerate(khc.feature_used_names_[:3]):
print(f"{feature} - Importance: {khc.feature_used_importances_[i][2]}")
print("---")
# Predict the classes on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[0:10])
print("---")
# Predict the class probabilities on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[0:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas[:, 1])
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
# If you have Khiops Visualization installed you may open the report as follows
# khc.export_report_file("report.khj")
# kh.visualize_report("report.khj")
def khiops_classifier_multiclass():
"""Trains a multiclass `.KhiopsClassifier` on a monotable dataframe"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Load the dataset into a pandas dataframe
iris_path = os.path.join(kh.get_samples_dir(), "Iris", "Iris.txt")
iris_df = pd.read_csv(iris_path, sep="\t")
# Split the whole dataframe into train and test (70%-30%)
iris_train_df, iris_test_df = train_test_split(
iris_df, test_size=0.3, random_state=1
)
# Split the dataset into:
# - the X feature table
# - the y target vector ("Class" column)
X_train = iris_train_df.drop("Class", axis=1)
X_test = iris_test_df.drop("Class", axis=1)
y_train = iris_train_df["Class"]
y_test = iris_test_df["Class"]
# Create the classifier object
khc = KhiopsClassifier()
# Train the classifier
khc.fit(X_train, y_train)
# Predict the classes on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[:10])
print("---")
# Predict the class probabilities on the test datasets
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas, multi_class="ovr")
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_classifier_text():
"""Train a `.KhiopsClassifier` on a monotable dataframe with textual data"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Load the dataset into a pandas dataframe
data_table_path = os.path.join(
kh.get_samples_dir(), "NegativeAirlineTweets", "NegativeAirlineTweets.txt"
)
data_df = pd.read_csv(data_table_path, sep="\t")
# Split the whole dataframe into train and test (70%-30%)
data_train_df, data_test_df = train_test_split(
data_df, test_size=0.3, random_state=1
)
# Split the dataset into:
# - the X feature table
# - the y target vector ("negativereason" column)
X_train = data_train_df.drop("negativereason", axis=1)
X_test = data_test_df.drop("negativereason", axis=1)
y_train = data_train_df["negativereason"]
y_test = data_test_df["negativereason"]
# Set Pandas StringDType on the "text" column
X_train["text"] = X_train["text"].astype("string")
X_test["text"] = X_test["text"].astype("string")
# Create the classifier object
khc = KhiopsClassifier()
# Train the classifier
khc.fit(X_train, y_train)
# Show the feature importance info
print(f"Features evaluated: {khc.n_features_evaluated_}")
print(f"Features selected : {khc.n_features_used_}")
print("Top 3 used features")
for i, feature in enumerate(khc.feature_used_names_[:3]):
print(f"{feature} - Importance: {khc.feature_used_importances_[i][2]}")
print("---")
# Predict the classes on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[0:10])
print("---")
# Predict the class probabilities on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[0:10])
print("---")
# Evaluate the accuracy metric on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
print(f"Test accuracy = {test_accuracy}")
# If you have Khiops Visualization installed you may open the report as follows
# khc.export_report_file("report.khj")
# kh.visualize_report("report.khj")
def khiops_classifier_multitable_star():
"""Trains a `.KhiopsClassifier` on a star multi-table dataset"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier, train_test_split_dataset
from sklearn import metrics
# Load the dataset into pandas dataframes
accidents_data_dir = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
accidents_df = pd.read_csv(
os.path.join(accidents_data_dir, "Accidents.txt"),
sep="\t",
)
vehicles_df = pd.read_csv(
os.path.join(accidents_data_dir, "Vehicles.txt"), sep="\t"
)
# Create the dataset spec and the target
X = {
"main_table": (accidents_df.drop("Gravity", axis=1), ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (vehicles_df, ["AccidentId", "VehicleId"]),
},
}
y = accidents_df["Gravity"]
# Split the dataset into train and test
X_train, X_test, y_train, y_test = train_test_split_dataset(
X, y, test_size=0.3, random_state=1
)
# Train the classifier (by default it analyzes 100 multi-table features)
khc = KhiopsClassifier()
khc.fit(X_train, y_train)
# Predict the class on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[:10])
print("---")
# Predict the class probability on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas[:, 1])
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_classifier_multitable_snowflake():
"""Trains a `.KhiopsClassifier` on a snowflake multi-table dataset"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier, train_test_split_dataset
from sklearn import metrics
# Load the dataset tables into dataframes
accidents_data_dir = os.path.join(kh.get_samples_dir(), "Accidents")
accidents_df = pd.read_csv(
os.path.join(accidents_data_dir, "Accidents.txt"), sep="\t"
)
users_df = pd.read_csv(os.path.join(accidents_data_dir, "Users.txt"), sep="\t")
vehicles_df = pd.read_csv(
os.path.join(accidents_data_dir, "Vehicles.txt"), sep="\t"
)
places_df = pd.read_csv(
os.path.join(accidents_data_dir, "Places.txt"), sep="\t", low_memory=False
)
# Build the multi-table dataset spec (drop the target column "Gravity")
X = {
"main_table": (accidents_df.drop("Gravity", axis=1), ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (vehicles_df, ["AccidentId", "VehicleId"]),
"Vehicles/Users": (users_df, ["AccidentId", "VehicleId"]),
"Places": (places_df, ["AccidentId"], True),
},
}
# Load the target variable "Gravity"
y = accidents_df["Gravity"]
# Split into train and test datasets
X_train, X_test, y_train, y_test = train_test_split_dataset(X, y)
# Train the classifier (by default it creates 1000 multi-table features)
khc = KhiopsClassifier(n_trees=0)
khc.fit(X_train, y_train)
# Show the feature importance info
print(f"Features evaluated: {khc.n_features_evaluated_}")
print(f"Features selected : {khc.n_features_used_}")
print("Top 3 used features")
for i, feature in enumerate(khc.feature_used_names_[:3]):
print(f"{feature} - Importance: {khc.feature_used_importances_[i][2]}")
print("---")
# Predict the class on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[:10])
print("---")
# Predict the class probability on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test_pred, y_test)
test_auc = metrics.roc_auc_score(y_test, y_test_probas[:, 1])
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_classifier_sparse():
"""Trains a `.KhiopsClassifier` on a monotable sparse matrix"""
# Imports
from khiops.sklearn import KhiopsClassifier
from sklearn import metrics
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import HashingVectorizer
# Load 3 classes of the 20newsgroups dataset
categories = ["comp.graphics", "sci.space", "misc.forsale"]
data_train, y_train = fetch_20newsgroups(
subset="train",
categories=categories,
return_X_y=True,
)
data_test, y_test = fetch_20newsgroups(
subset="test",
categories=categories,
return_X_y=True,
)
# Extract features from the training data using a sparse vectorizer
vectorizer = HashingVectorizer(n_features=2**10, stop_words="english")
X_train = vectorizer.fit_transform(data_train)
# Extract features from the test data using the same vectorizer
X_test = vectorizer.transform(data_test)
# Create the classifier object
khc = KhiopsClassifier()
# Train the classifier
khc.fit(X_train, y_train)
# Predict the classes on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[0:10])
print("---")
# Predict the class probabilities on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[0:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas, multi_class="ovr")
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_classifier_pickle():
"""Shows the serialization and deserialization of a `.KhiopsClassifier`"""
# Imports
import os
import pandas as pd
import pickle
from khiops.sklearn import KhiopsClassifier
# Create/clean the output directory
results_dir = os.path.join("kh_samples", "khiops_classifier_pickle")
khc_pickle_path = os.path.join(results_dir, "khiops_classifier.pkl")
if os.path.exists(khc_pickle_path):
os.remove(khc_pickle_path)
else:
os.makedirs(results_dir, exist_ok=True)
# Load the "Iris" dataset
iris_path = os.path.join(kh.get_samples_dir(), "Iris", "Iris.txt")
iris_df = pd.read_csv(iris_path, sep="\t")
X = iris_df.drop("Class", axis=1)
y = iris_df["Class"]
# Train the model with the Iris dataset
khc = KhiopsClassifier()
khc.fit(X, y)
# Pickle its content to a file
with open(khc_pickle_path, "wb") as khc_pickle_output_file:
pickle.dump(khc, khc_pickle_output_file)
# Unpickle it
with open(khc_pickle_path, "rb") as khc_pickle_file:
new_khc = pickle.load(khc_pickle_file)
# Make some predictions on the training dataset with the unpickled classifier
new_khc.predict(X)
y_predicted = new_khc.predict(X)
print("Predicted classes (first 10):")
print(y_predicted[:10])
print("---")
def khiops_classifier_with_hyperparameters():
"""Trains a `.KhiopsClassifier` on a star multi-table dataset
(advanced version with more hyperparameters)
"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsClassifier
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Load the root table of the dataset into a pandas dataframe
accidents_dataset_path = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
accidents_df = pd.read_csv(
os.path.join(accidents_dataset_path, "Accidents.txt"),
sep="\t",
)
# Split the root dataframe into train and test
accidents_train_df, accidents_test_df = train_test_split(
accidents_df, test_size=0.3, random_state=1
)
# Obtain the main X feature table and the y target vector ("Class" column)
y_train = accidents_train_df["Gravity"]
y_test = accidents_test_df["Gravity"]
X_train_main = accidents_train_df.drop("Gravity", axis=1)
X_test_main = accidents_test_df.drop("Gravity", axis=1)
# Load the secondary table of the dataset into a pandas dataframe
vehicles_df = pd.read_csv(
os.path.join(accidents_dataset_path, "Vehicles.txt"), sep="\t"
)
# Split the secondary dataframe with the keys of the split root dataframe
X_train_ids = X_train_main["AccidentId"].to_frame()
X_test_ids = X_test_main["AccidentId"].to_frame()
X_train_secondary = X_train_ids.merge(vehicles_df, on="AccidentId")
X_test_secondary = X_test_ids.merge(vehicles_df, on="AccidentId")
# Create the dataset multitable specification for the train/test split
# We specify each table with a name and a tuple (dataframe, key_columns)
X_train = {
"main_table": (X_train_main, ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (X_train_secondary, ["AccidentId", "VehicleId"]),
},
}
X_test = {
"main_table": (X_test_main, ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (X_test_secondary, ["AccidentId", "VehicleId"]),
},
}
# Train the classifier (by default it analyzes 100 multi-table features)
khc = KhiopsClassifier(
n_features=20,
n_pairs=5,
n_trees=5,
n_selected_features=10,
n_evaluated_features=15,
specific_pairs=[("Light", "Weather"), ("Light", "IntersectionType")],
all_possible_pairs=True,
construction_rules=["TableMode", "TableSelection"],
group_target_value=False,
)
khc.fit(X_train, y_train)
# Predict the class on the test dataset
y_test_pred = khc.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[:10])
print("---")
# Predict the class probability on the test dataset
y_test_probas = khc.predict_proba(X_test)
print(f"Class order: {khc.classes_}")
print("Predicted class probabilities (first 10):")
print(y_test_probas[:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas[:, 1])
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_regressor():
"""Trains a `.KhiopsRegressor` on a monotable dataframe"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsRegressor
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Load the "Adult" dataset and set the target to the "age" column
adult_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
adult_df = pd.read_csv(adult_path, sep="\t")
X = adult_df.drop("age", axis=1)
y = adult_df["age"]
# Split the whole dataframe into train and test (40%-60% for speed)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1
)
# Create the regressor object
khr = KhiopsRegressor()
# Train the regressor
khr.fit(X_train, y_train)
# Show the feature importance info
print(f"Features evaluated: {khr.n_features_evaluated_}")
print(f"Features selected : {khr.n_features_used_}")
print("Top 3 used features")
for i, feature in enumerate(khr.feature_used_names_[:3]):
print(f"{feature} - Importance: {khr.feature_used_importances_[i][2]}")
print("---")
# Predict the values on the test dataset
y_test_pred = khr.predict(X_test)
print("Predicted values for 'age' (first 10):")
print(y_test_pred[:10])
print("---")
# Evaluate R2 and MAE metrics on the test dataset
test_r2 = metrics.r2_score(y_test, y_test_pred)
test_mae = metrics.mean_absolute_error(y_test, y_test_pred)
print(f"Test R2 = {test_r2}")
print(f"Test MAE = {test_mae}")
# If you have Khiops Visualization installed you may open the report as follows
# khr.export_report_file("report.khj")
# kh.visualize_report("report.khj")
def khiops_encoder():
"""Trains a `.KhiopsEncoder` on a monotable dataframe
The Khiops encoder is a supervised feature encoder. It discretizes numerical
features and groups categorical features in a way that the resulting interval/groups
have the highest class-purity.
.. note::
For simplicity we train from the whole dataset. To assess the performance one
usually splits the dataset into train and test subsets.
"""
# Imports
import pandas as pd
from khiops.sklearn import KhiopsEncoder
# Load the dataset
iris_path = os.path.join(kh.get_samples_dir(), "Iris", "Iris.txt")
iris_df = pd.read_csv(iris_path, sep="\t")
X = iris_df.drop("Class", axis=1)
y = iris_df["Class"]
# Create the encoder object
khe = KhiopsEncoder(transform_type_numerical="part_label")
khe.fit(X, y)
# Transform the training dataset
X_transformed = khe.transform(X)
# Print both the original and transformed features
print("Original:")
print(X[:10])
print("---")
print("Encoded feature names:")
print(khe.feature_names_out_)
print("Encoded data:")
print(X_transformed[:10])
print("---")
# If you have Khiops Visualization installed you may open the report as follows
# khe.export_report_file("report.khj")
# kh.visualize_report("report.khj")
def khiops_encoder_multitable_star():
"""Trains a `.KhiopsEncoder` on a star multi-table dataset"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsEncoder
# Load the dataset tables into dataframe
accidents_data_dir = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
accidents_df = pd.read_csv(
os.path.join(accidents_data_dir, "Accidents.txt"),
sep="\t",
)
vehicles_df = pd.read_csv(
os.path.join(accidents_data_dir, "Vehicles.txt"), sep="\t"
)
# Build the multi-table dataset spec (drop the target column "Gravity")
X = {
"main_table": (accidents_df.drop("Gravity", axis=1), ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (vehicles_df, ["AccidentId", "VehicleId"]),
},
}
# Load the target variable "Gravity"
y = accidents_df["Gravity"]
# Create the KhiopsEncoder with 5 multitable features and fit it
khe = KhiopsEncoder(n_features=10)
khe.fit(X, y)
# Transform the train dataset
print("Encoded feature names:")
print(khe.feature_names_out_)
print("Encoded data:")
print(khe.transform(X)[:10])
def khiops_encoder_multitable_snowflake():
"""Trains a `.KhiopsEncoder` on a snowflake multi-table dataset"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsEncoder
# Load the tables into dataframes
accidents_data_dir = os.path.join(kh.get_samples_dir(), "Accidents")
accidents_df = pd.read_csv(
os.path.join(accidents_data_dir, "Accidents.txt"), sep="\t"
)
users_df = pd.read_csv(os.path.join(accidents_data_dir, "Users.txt"), sep="\t")
vehicles_df = pd.read_csv(
os.path.join(accidents_data_dir, "Vehicles.txt"), sep="\t"
)
places_df = pd.read_csv(
os.path.join(accidents_data_dir, "Places.txt"), sep="\t", low_memory=False
)
# Build the multi-table dataset spec (drop the target column "Gravity")
X = {
"main_table": (accidents_df.drop("Gravity", axis=1), ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (vehicles_df, ["AccidentId", "VehicleId"]),
"Vehicles/Users": (users_df, ["AccidentId", "VehicleId"]),
"Places": (places_df, ["AccidentId"], True),
},
}
# Load the target variable "Gravity"
y = accidents_df["Gravity"]
# Create the KhiopsEncoder with 10 additional multitable features and fit it
khe = KhiopsEncoder(n_features=10)
khe.fit(X, y)
# Show the feature importance info
print(f"Features evaluated: {khe.n_features_evaluated_}")
print("Top 3 evaluated features")
for i, feature in enumerate(khe.feature_evaluated_names_[:3]):
print(f"{feature} - Level: {khe.feature_evaluated_importances_[i]}")
print("---")
# Transform the train dataset
print("Encoded feature names:")
print(khe.feature_names_out_)
print("Encoded data:")
print(khe.transform(X)[:10])
# Disable line too long just to have a title linking the sklearn documentation
# pylint: disable=line-too-long
def khiops_encoder_pipeline_with_hgbc():
"""Uses a `.KhiopsEncoder` with a `~sklearn.ensemble.HistGradientBoostingClassifier`"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsEncoder
from sklearn import metrics
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
# Load the dataset into dataframes
adult_path = os.path.join(kh.get_samples_dir(), "Adult", "Adult.txt")
adult_df = pd.read_csv(adult_path, sep="\t")
X = adult_df.drop("class", axis=1)
y = adult_df["class"]
# Split the dataset into train and test (70%-30%)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1
)
# Create the pipeline and fit it. Steps:
# - The khiops supervised column encoder, generates a full-categorical table
# - One hot encoder in all columns
# - Train the HGB classifier
pipe_steps = [
("khiops_enc", KhiopsEncoder()),
(
"onehot_enc",
ColumnTransformer([], remainder=OneHotEncoder(sparse_output=False)),
),
("hgb_clf", HistGradientBoostingClassifier()),
]
pipe = Pipeline(pipe_steps)
pipe.fit(X_train, y_train)
# Predict the classes on the test dataset
y_test_pred = pipe.predict(X_test)
print("Predicted classes (first 10):")
print(y_test_pred[:10])
print("---")
# Predict the class probabilities on the test dataset
y_test_probas = pipe.predict_proba(X_test)
print("Predicted class probabilities (first 10):")
print(y_test_probas[:10])
print("---")
# Evaluate accuracy and auc metrics on the test dataset
test_accuracy = metrics.accuracy_score(y_test, y_test_pred)
test_auc = metrics.roc_auc_score(y_test, y_test_probas[:, 1])
print(f"Test accuracy = {test_accuracy}")
print(f"Test auc = {test_auc}")
def khiops_encoder_with_hyperparameters():
"""Trains a `.KhiopsEncoder` on a star multi-table dataset
(advanced version with more hyperparameters)
"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsEncoder
# Load the tables into dataframes
accidents_data_dir = os.path.join(kh.get_samples_dir(), "AccidentsSummary")
accidents_df = pd.read_csv(
os.path.join(accidents_data_dir, "Accidents.txt"), sep="\t"
)
vehicles_df = pd.read_csv(
os.path.join(accidents_data_dir, "Vehicles.txt"), sep="\t"
)
# Build the multi-table dataset spec (drop the target column "Gravity")
X = {
"main_table": (accidents_df.drop("Gravity", axis=1), ["AccidentId"]),
"additional_data_tables": {
"Vehicles": (vehicles_df, ["AccidentId", "VehicleId"]),
},
}
# Load the target variable "Gravity"
y = accidents_df["Gravity"]
# Create the KhiopsEncoder with 10 additional multitable features and fit it
khe = KhiopsEncoder(
n_features=20,
n_pairs=5,
n_trees=5,
specific_pairs=[("Light", "Weather"), ("Light", "IntersectionType")],
all_possible_pairs=True,
construction_rules=["TableMode", "TableSelection"],
group_target_value=False,
informative_features_only=True,
keep_initial_variables=True,
transform_type_categorical="part_id",
transform_type_numerical="part_id",
transform_type_pairs="part_id",
)
khe.fit(X, y)
# Transform the train dataset
print("Encoded feature names:")
print(khe.feature_names_out_)
print("Encoded data:")
print(khe.transform(X)[:10])
# pylint: enable=line-too-long
def khiops_coclustering():
"""Trains a `.KhiopsCoclustering` on a dataframe"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsCoclustering
from sklearn.model_selection import train_test_split
# Load the secondary table of the dataset into a pandas dataframe
splice_data_dir = os.path.join(kh.get_samples_dir(), "SpliceJunction")
splice_dna_df = pd.read_csv(
os.path.join(splice_data_dir, "SpliceJunctionDNA.txt"), sep="\t"
)
# Train with only 70% of data (for speed in this example)
X, _ = train_test_split(splice_dna_df, test_size=0.3, random_state=1)
# Create the KhiopsCoclustering instance
khcc = KhiopsCoclustering()
# Train the model with the whole dataset
khcc.fit(X, id_column="SampleId")
# Predict the clusters in some instances
X_clusters = khcc.predict(X)
print("Predicted clusters (first 10)")
print(X_clusters[:10])
print("---")
# If you have Khiops Co-Visualization installed you may open the report as follows
# khcc.export_report_file("report.khcj")
# kh.visualize_report("report.khcj")
def khiops_coclustering_simplify():
"""Simplifies a `.KhiopsCoclustering` already trained on a dataframe"""
# Imports
import os
import pandas as pd
from khiops import core as kh
from khiops.sklearn import KhiopsCoclustering
from sklearn.model_selection import train_test_split
# Load the secondary table of the dataset into a pandas dataframe
splice_data_dir = os.path.join(kh.get_samples_dir(), "SpliceJunction")
splice_dna_X = pd.read_csv(
os.path.join(splice_data_dir, "SpliceJunctionDNA.txt"), sep="\t"
)
# Train with only 70% of data (for speed in this example)
X, _ = train_test_split(splice_dna_X, test_size=0.3, random_state=1)
# Create the KhiopsCoclustering instance
khcc = KhiopsCoclustering()
# Train the model with the whole dataset
khcc.fit(X, id_column="SampleId")
# Simplify coclustering along the individual ID dimension
simplified_khcc = khcc.simplify(max_part_numbers={"SampleId": 3})
# Predict the clusters using the simplified model
X_clusters = simplified_khcc.predict(X)
print("Predicted clusters (only three at most)")
print(X_clusters)
print("---")
exported_samples = [
khiops_classifier,
khiops_classifier_multiclass,
khiops_classifier_text,
khiops_classifier_multitable_star,
khiops_classifier_multitable_snowflake,
khiops_classifier_sparse,
khiops_classifier_pickle,
khiops_classifier_with_hyperparameters,
khiops_regressor,
khiops_encoder,
khiops_encoder_multitable_star,
khiops_encoder_multitable_snowflake,
khiops_encoder_pipeline_with_hgbc,
khiops_encoder_with_hyperparameters,
khiops_coclustering,
khiops_coclustering_simplify,
]
def execute_samples(args):
"""Executes all non-interactive samples"""
# Create the results directory if it does not exist
os.makedirs("./kh_samples", exist_ok=True)
# Set the user-defined samples dir if any
if args.samples_dir is not None:
kh.get_runner().samples_dir = args.samples_dir
if args.include is not None:
execution_samples = filter_samples(
exported_samples, args.include, args.exact_match
)
else:
execution_samples = exported_samples
# Print the execution title
if execution_samples:
print(f"Khiops Python library {khiops.__version__} running on Khiops ", end="")
print(f"{kh.get_khiops_version()}\n")
print(f"Sample datasets location: {kh.get_samples_dir()}")
print(f"{len(execution_samples)} sample(s) to execute\n")
for sample in execution_samples:
print(f">>> Executing samples_sklearn.{sample.__name__}")
sample.__call__()
print("> Done\n")
print("*** Samples run! ****")
else:
print("*** No samples to run ***")
def filter_samples(sample_list, include, exact_match):
"""Filter the samples according to the command line options"""
filtered_samples = []
for sample in sample_list:
for sample_name in include:
if (exact_match and sample_name == sample.__name__) or (
not exact_match and sample_name in sample.__name__
):
filtered_samples.append(sample)
return filtered_samples
def build_argument_parser(prog, description):
"""Samples argument parser builder function
Parameters
----------
prog : str
Name of the program, as required by the argument parser.
description : str
Description of the program, as required by the argument parser.
Returns
-------
ArgumentParser
Argument parser object.
"""
parser = argparse.ArgumentParser(
prog=prog,
formatter_class=argparse.RawTextHelpFormatter,
description=description,
)
parser.add_argument(
"-d",
"--samples-dir",
metavar="URI",
help="Location of the Khiops 'samples' directory",
)
parser.add_argument(
"-i", "--include", nargs="*", help="Executes only the tests matching this list"
)
parser.add_argument(
"-e",
"--exact-match",
action="store_true",
help="Matches with --include are exact",