-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
2451 lines (1989 loc) · 108 KB
/
app.py
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
# this app has developed by Idriss khattabi - Mohammed Amine Sabbahi - Aymen Boufarhi
import customtkinter as ctk
from PIL import Image
import tkinter.filedialog as fd
import tkinter as tk
from tkinter import ttk
from CTkMessagebox import CTkMessagebox
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import os
import io
import contextlib
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer, RobustScaler, PowerTransformer, QuantileTransformer, LabelEncoder
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.svm import SVR, SVC
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.cluster import KMeans
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, auc
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error, explained_variance_score
# *********************************************************************************
ctk.set_appearance_mode("dark")
app = ctk.CTk()
app.geometry('1200x1000')
app.iconbitmap('images/icon.ico')
app.title('ModelMaster')
dataset = None
creat_file_path = None
# Fonction permet de cree un jeu de donnees
def creat_dataset():
global creat_file_path
# Create a sample DataFrame (you can replace this with your dataset creation logic)
creat_file_path = fd.asksaveasfilename(defaultextension=".xlsx", filetypes=[("Excel files", "*.xlsx")])
# Check if the user canceled file selection
if not creat_file_path:
return
# Create a sample DataFrame (you can replace this with your dataset creation logic)
example_data = {
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C']
}
df = pd.DataFrame(example_data)
# Write the DataFrame to the selected Excel file
df.to_excel(creat_file_path, index=False)
# Check if the file was created successfully
if os.path.exists(creat_file_path):
try:
os.startfile(creat_file_path)
except Exception as e:
CTkMessagebox(title="Warning", message=f"Failed to open Excel: {e}", icon="warning", option_1="Ok")
else:
CTkMessagebox(title="Warning", message=f"Failed to creat dataset", icon="cancel", option_1="Ok")
# Fonction permet de Import un jeu de donnees
def import_dataset():
global dataset
filetypes = [
("CSV Files", "*.csv"),
("Excel Files", "*.xlsx"),
("Text Files", "*.txt"),
("All Files", "*.*")
]
file_path = ctk.filedialog.askopenfilename(filetypes=filetypes)
if file_path:
try:
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == ".csv":
dataset = pd.read_csv(file_path, dtype=object)
elif file_extension == ".xlsx":
dataset = pd.read_excel(file_path, dtype=object)
elif file_extension == ".txt":
dataset = pd.read_csv(file_path, dtype=object, delimiter='\t') # Assuming it's tab-separated
else:
raise ValueError("Unsupported file format")
if dataset is not None :
show_table(dataset, table_frame)
except Exception as e:
CTkMessagebox(title="Warning", message=f"Failed to load dataset: {e}", icon="warning", option_1="Ok")
table_frame = None
columns_list = None
# Fonction permet de afficher la table de jeu de donnees danse la page Import
def show_table(data, frame):
global columns_list
if data is not None:
# Clear any existing data in the table_frame
for widget in frame.winfo_children():
widget.destroy()
columns_list = data.columns.tolist()
style = ttk.Style()
style.configure('Alternate.Treeview', background='lightblue', fieldbackground='white', font=('Courier', 15))
# Configure the separator style for columns
style.layout('Treeview', [('Treeview.treearea', {'sticky': 'nswe'})]) # Set separator style
# Create a Treeview widget
tree = ttk.Treeview(frame, columns=columns_list, show="headings", selectmode="extended")
tree.config(style='Alternate.Treeview')
# Set up columns
for col in columns_list:
tree.heading(col, text=col, anchor=tk.CENTER) # Center-align headings
tree.column(col, width=100, anchor=tk.CENTER) # Adjust width as needed
# Insert data into the table
for index, row in data.iterrows():
tree.insert("", "end", values=row.tolist())
# Add a vertical scrollbar
vsb = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
vsb.pack(side="right", fill="y")
tree.configure(yscrollcommand=vsb.set)
# Add a horizontal scrollbar
hsb = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
hsb.pack(side="bottom", fill="x")
tree.configure(xscrollcommand=hsb.set)
tree.pack(fill='both', expand=True)
else:
CTkMessagebox(title="Error", message="No Data to display!", icon="cancel", option_1="Ok")
target_name = ""
target_type = ""
def submit_values():
global target_name, target_type, dataset, columns_list, table_frame, creat_file_path
if creat_file_path is not None:
dataset = pd.read_excel(creat_file_path)
creat_file_path = None
columns_list = dataset.columns.tolist()
target_name = target_column.get()
target_type = label_type_var.get()
if dataset is not None:
if target_name != "" and target_type != "":
if target_name in columns_list:
show_table(dataset, table_frame)
CTkMessagebox(title="Done", message=f"The target name = '{target_name}', and target_type = '{target_type}' have saved seccussfully", icon="check", option_1="Ok")
else:
CTkMessagebox(title="Error", message=f"There is no column named {target_name} in the imported dataset", icon="cancel", option_1="Ok")
else:
CTkMessagebox(title="Error", message="Please specify the target column name and type first.", icon="cancel", option_1="Ok")
else:
CTkMessagebox(title="Error", message="No Data, Please import a dataset first.", icon="cancel", option_1="Ok")
# Les fonctiones de traitement de dataset
def update_info_list():
global dataset, dataset_info_var
with io.StringIO() as buf, contextlib.redirect_stdout(buf):
dataset.info()
info_output = buf.getvalue()
# Displaying the formatted output excluding the first three lines
info_lines = info_output.split('\n')
info_to_display = '\n'.join(info_lines[5:])
dataset_info_var.set(info_to_display)
def delete_columns():
global dataset, column_entry
cols = column_entry.get()
columns_to_drop = cols.split(',')
columns_to_drop = [s.strip() for s in columns_to_drop]
cnt = 0
for col in columns_to_drop:
if col in dataset.columns.tolist():
cnt += 1
if cnt == len(columns_to_drop):
dataset.drop(columns=columns_to_drop, axis=1, inplace=True)
update_table()
update_info_list()
CTkMessagebox(title="Success", message=f"Columns {" ".join(columns_to_drop)} deleted successfully.", icon="check", option_1="Ok")
column_entry.delete(0, 'end')
else:
CTkMessagebox(title="Error", message="Please enter columns name correctly.", icon="cancel", option_1="Ok")
column_entry.delete(0, 'end')
def update_table():
global dataset, process_frame
show_table(dataset, process_frame)
def features_scaling():
global dataset, fs_method_option, target_name
print(f"target_name : {target_name}")
if not target_name in dataset.columns or target_name == "":
print("you must choose the target column name in import Dataset Page to do feature scaling!!")
CTkMessagebox(title="Error", message="target_name is not define, PLZ choose the target column name in import Dataset Page to do feature scaling!!", icon="cancel", option_1="Ok")
return
if dataset is not None:
fs_method = fs_method_option.get()
scaler = None
if fs_method == "MinMaxScaler" :
print("MinMaxScaler")
scaler = MinMaxScaler()
elif fs_method == "StandardScaler" :
print("StandardScaler")
scaler = StandardScaler()
elif fs_method == "Normalizer" :
print("Normalizer")
scaler = Normalizer()
elif fs_method == "RobustScaler" :
print("RobustScaler")
scaler = RobustScaler()
elif fs_method == "PowerTransformer" :
print("PowerTransformer")
scaler = PowerTransformer()
else :
print("QuantileTransformer")
scaler = QuantileTransformer()
columns = dataset.columns
columns_without_target = columns.drop(target_name)
#print(pd.DataFrame(dataset[columns_without_target]))
dataset[columns_without_target] = scaler.fit_transform(dataset[columns_without_target])
update_table()
CTkMessagebox(title="Success", message=f"Features scaled successfully.", icon="check", option_1="Ok")
else:
CTkMessagebox(title="Error", message="No Data, Please import a dataset first.", icon="cancel", option_1="Ok")
def check_nan():
global dataset, check_label_var
columns_with_missing_values = dataset.isna().sum()
columns_with_missing_values = columns_with_missing_values[columns_with_missing_values > 0]
if dataset is not None:
check_label_var.set(f"{columns_with_missing_values}\nTotal: {columns_with_missing_values.sum()} missig values")
else:
CTkMessagebox(title="Error", message="No Data, Please import a dataset first.", icon="cancel", option_1="Ok")
def handle_data_by_method():
global dataset, method_option, mv_features
if dataset is not None:
method = method_option.get()
columns_to_handle = mv_features.get().split(',')
columns_to_handle = [s.strip() for s in columns_to_handle]
if method != "" and columns_to_handle != "":
if method == "Mean":
for col in columns_to_handle:
dataset[col].fillna(value=pd.to_numeric(dataset[col], errors='coerce').mean(), inplace=True)
elif method == "Max":
for col in columns_to_handle:
dataset[col].fillna(value=pd.to_numeric(dataset[col], errors='coerce').max(), inplace=True)
elif method == "Min":
for col in columns_to_handle:
dataset[col].fillna(value=pd.to_numeric(dataset[col], errors='coerce').min(), inplace=True)
elif method == "Previous value":
for col in columns_to_handle:
dataset[col].fillna(method='ffill', inplace=True)
elif method == "Next value":
for col in columns_to_handle:
dataset[col].fillna(method='bfill', inplace=True)
elif method == "Delete row":
dataset.dropna(inplace=True)
mv_features.delete(0, 'end')
update_table()
update_info_list()
CTkMessagebox(title="Success", message=f"Missing Values Handled successfully.", icon="check", option_1="Ok")
else:
CTkMessagebox(title="Error", message="Please specify method and features.", icon="cancel", option_1="Ok")
mv_features.delete(0, 'end')
check_nan()
else:
CTkMessagebox(title="Error", message="Please specify method and features.", icon="cancel", option_1="Ok")
def handle_data_by_value():
global value_entry, na_by_value_entry
if dataset is not None:
value = value_entry.get()
features = na_by_value_entry.get().split(',')
features = [s.strip() for s in features]
if value != "" and features != "":
for col in features:
dataset[col].fillna(value=value, inplace=True)
mv_features.delete(0, 'end')
update_table()
update_info_list()
CTkMessagebox(title="Success", message=f"Missing Values Handled successfully.", icon="check", option_1="Ok")
else:
CTkMessagebox(title="Error", message="Please specify value and features correctly.", icon="cancel", option_1="Ok")
na_by_value_entry.delete(0, 'end')
value_entry.delete(0, 'end')
check_nan()
else:
CTkMessagebox(title="Error", message="No Data, Please import a dataset first.", icon="cancel", option_1="Ok")
na_by_value_entry.delete(0, 'end')
value_entry.delete(0, 'end')
def data_encoding():
global dataset, encoding_entry, encodin_value_entry, encodin_cat_value_entry
feature = encoding_entry.get()
value = encodin_value_entry.get()
cat_value = encodin_cat_value_entry.get()
if dataset is not None:
if feature in dataset.columns.tolist():
dataset[feature] = dataset[feature].replace(cat_value, value)
update_table()
CTkMessagebox(title="Success", message=f"The data encoded successfully.", icon="check", option_1="Ok")
else:
CTkMessagebox(title="Error", message="Please enter a feature from the dataset.", icon="cancel", option_1="Ok")
encodin_value_entry.delete(0, 'end')
encodin_cat_value_entry.delete(0, 'end')
else:
CTkMessagebox(title="Error", message="No Data, Please import a dataset first.", icon="cancel", option_1="Ok")
encodin_value_entry.delete(0, 'end')
encodin_cat_value_entry.delete(0, 'end')
def export_dataset():
global dataset
if dataset is not None:
filetypes = [
("CSV Files", "*.csv"),
("Excel Files", "*.xlsx"),
("Text Files", "*.txt")
]
file_path = ctk.filedialog.asksaveasfilename(filetypes=filetypes, defaultextension=filetypes[0])
if file_path:
try:
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == ".csv":
dataset.to_csv(file_path, index=False)
elif file_extension == ".xlsx":
dataset.to_excel(file_path, index=False)
elif file_extension == ".txt":
dataset.to_csv(file_path, index=False, sep='\t')
else:
raise ValueError("Unsupported file format")
CTkMessagebox(title="Success", message=f"Dataset saved successfully to:\n{file_path}", icon="check", option_1="Ok")
except Exception as e:
CTkMessagebox(title="Error", message=f"Failed to save dataset: {e}", icon="cancel", option_1="Ok")
else:
CTkMessagebox(title="Error", message="No Data to export!", icon="cancel", option_1="Ok")
# *** Les Fonctiones des algorithmes ML *** :
model = None
repport1 = None
accuracy1 = None
classifier1 = None
y_pred1 = None
y_test1 = None
def native_bayes(ts):
global dataset, target_name, repport1, accuracy1, classifier1, y_pred1, y_test1
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Naive Bayes model
nb_classifier = GaussianNB()
nb_classifier.fit(X_train, y_train)
# Predict on the test set
y_pred = nb_classifier.predict(X_test)
# Evaluate the model
accuracy1 = accuracy_score(y_test, y_pred)
# Display classification report
repport1 = classification_report(y_test, y_pred)
classifier1 = nb_classifier
y_pred1 = y_pred
y_test1 = y_test
repport2 = None
accuracy2 = None
classifier2 = None
y_pred2 = None
y_test2 = None
def random_forest(ts):
global dataset, target_name, repport2, accuracy2, classifier2, y_test2, y_pred2
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Random Forest model
rf_classifier = RandomForestClassifier()
rf_classifier.fit(X_train, y_train)
# Predict on the test set
y_pred = rf_classifier.predict(X_test)
# Evaluate the model
accuracy2 = accuracy_score(y_test, y_pred)
# Display classification report
repport2 = classification_report(y_test, y_pred)
classifier2 = rf_classifier
y_pred2 = y_pred
y_test2 = y_test
repport3 = None
accuracy3 = None
classifier3 = None
y_pred3 = None
y_test3 = None
def decision_tree(ts):
global dataset, target_name, repport3, accuracy3, classifier3, y_pred3, y_test3
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Naive Bayes model
dt_classifier = DecisionTreeClassifier(max_depth=3, min_samples_split=5)
dt_classifier.fit(X_train, y_train)
# Predict on the test set
y_pred = dt_classifier.predict(X_test)
# Evaluate the model
accuracy3 = accuracy_score(y_test, y_pred)
# Display classification report
repport3 = classification_report(y_test, y_pred)
classifier3 = dt_classifier
y_pred3 = y_pred
y_test3 = y_test
repport4 = None
accuracy4 = None
classifier4 = None
y_pred4 = None
y_test4 = None
def knn(ts):
global dataset, target_name, repport4, accuracy4, classifier4, y_pred4, y_test4
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Naive Bayes model
knn_classifier = KNeighborsClassifier()
knn_classifier.fit(X_train, y_train)
classifier4 = knn_classifier
# Predict on the test set
y_pred = knn_classifier.predict(X_test)
y_pred4 = y_pred
y_test4 = y_test
# Evaluate the model
accuracy4 = accuracy_score(y_test, y_pred)
# Display classification report
repport4 = classification_report(y_test, y_pred)
repport5 = None
accuracy5 = None
classifier5 = None
y_pred5 = None
y_test5 = None
def sv_classifier(ts):
global dataset, target_name, repport5, accuracy5, classifier5, y_pred5, y_test5
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Naive Bayes model
svc = SVC(kernel='linear')
svc.fit(X_train, y_train)
# Predict on the test set
y_pred = svc.predict(X_test)
# Evaluate the model
accuracy5 = accuracy_score(y_test, y_pred)
# Display classification report
repport5 = classification_report(y_test, y_pred)
classifier5 = svc
y_pred5 = y_pred
y_test5 = y_test
repport6 = None
accuracy6 = None
classifier6 = None
y_pred6 = None
y_test6 = None
def nn_classifier(ts):
global dataset, target_name, repport6, accuracy6, classifier6, y_pred6, y_test6
if dataset is not None:
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
if len(categorical_cols) > 0:
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Initialize and fit the Naive Bayes model
nnc = MLPClassifier(hidden_layer_sizes=(100,), max_iter=1000)
nnc.fit(X_train, y_train)
# Predict on the test set
y_pred = nnc.predict(X_test)
# Evaluate the model
accuracy6 = accuracy_score(y_test, y_pred)
# Display classification report
repport6 = classification_report(y_test, y_pred)
classifier6 = nnc
y_pred6 = y_pred
y_test6 = y_test
def apply_ml_classifiers():
ts = float(test_size.get())
print(ts)
native_bayes(ts)
random_forest(ts)
decision_tree(ts)
knn(ts)
sv_classifier(ts)
nn_classifier(ts)
if dataset is not None:
# Text area 1 modification
text_area1.config(state=tk.NORMAL) # Set state to normal to modify
text_area1.delete(1.0, tk.END) # Clear previous content
text_area1.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy1 * 100:.2f}%\n\n")
text_area1.insert(tk.END, f"\n\n {repport1}") # Insert new classification report
text_area1.config(state=tk.DISABLED)
# Text area 2 modification
text_area2.config(state=tk.NORMAL) # Set state to normal to modify
text_area2.delete(1.0, tk.END) # Clear previous content
text_area2.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy2 * 100:.2f}\n\n")
text_area2.insert(tk.END, f"\n\n {repport2}") # Insert new classification report
text_area2.config(state=tk.DISABLED)
# Text area 3 modification
text_area3.config(state=tk.NORMAL) # Set state to normal to modify
text_area3.delete(1.0, tk.END) # Clear previous content
text_area3.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy3 * 100:.2f}\n\n")
text_area3.insert(tk.END, f"\n\n {repport3}") # Insert new classification report
text_area3.config(state=tk.DISABLED)
# Text area 4 modification
text_area4.config(state=tk.NORMAL) # Set state to normal to modify
text_area4.delete(1.0, tk.END) # Clear previous content
text_area4.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy4 * 100:.2f}\n\n")
text_area4.insert(tk.END, f"\n\n {repport4}") # Insert new classification report
text_area4.config(state=tk.DISABLED)
# Text area 5 modification
text_area5.config(state=tk.NORMAL) # Set state to normal to modify
text_area5.delete(1.0, tk.END) # Clear previous content
text_area5.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy5 * 100:.2f}\n\n")
text_area5.insert(tk.END, f"\n\n {repport5}") # Insert new classification report
text_area5.config(state=tk.DISABLED)
# Text area 5 modification
text_area6.config(state=tk.NORMAL) # Set state to normal to modify
text_area6.delete(1.0, tk.END) # Clear previous content
text_area6.insert(tk.END, f"\t\t\t\tAccuracy: {accuracy6 * 100:.2f}\n\n")
text_area6.insert(tk.END, f"\n\n {repport6}") # Insert new classification report
text_area6.config(state=tk.DISABLED)
else:
CTkMessagebox(title="Error",
message="No Data, Please import a dataset first.",
icon="cancel",
option_1="Ok")
mse1 = None
mae1 = None
r21 = None
explained_var1 = None
y_pred21 = None
y_test21 = None
predictor1 = None
def Linear_Regression(ts):
global dataset, mse1, mae1, r21, explained_var1, target_name, y_pred21, y_test21, predictor1
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the Linear Regression model
l_regressor = LinearRegression()
l_regressor.fit(X_train, y_train)
# Make predictions
y_pred = l_regressor.predict(X_test)
# Evaluate the model
mse1 = mean_squared_error(y_test, y_pred)
mae1 = mean_absolute_error(y_test, y_pred)
r21 = r2_score(y_test, y_pred)
explained_var1 = explained_variance_score(y_test, y_pred)
y_pred21 = y_pred
y_test21 = y_test
predictor1 = l_regressor
mse2 = None
mae2 = None
r22 = None
explained_var2 = None
y_pred22 = None
y_test22 = None
predictor2 = None
def SV_Regression(ts):
global dataset, mse2, mae2, r22, explained_var2, target_name, y_pred22, y_test22, predictor2
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the SVR model
sv_regressor = SVR()
sv_regressor.fit(X_train, y_train)
# Make predictions
y_pred = sv_regressor.predict(X_test)
# Evaluate the model
mse2 = mean_squared_error(y_test, y_pred)
mae2 = mean_absolute_error(y_test, y_pred)
r22 = r2_score(y_test, y_pred)
explained_var2 = explained_variance_score(y_test, y_pred)
y_pred22 = y_pred
y_test22 = y_test
predictor2 = sv_regressor
mse3 = None
mae3 = None
r23 = None
explained_var3 = None
y_pred23 = None
y_test23 = None
predictor3 = None
def DT_Regression(ts):
global dataset, mse3, mae3, r23, explained_var3, target_name, y_test23, y_pred23, predictor3
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the Decision Tree Regression model
dt_regressor = DecisionTreeRegressor(max_depth=3, min_samples_split=5)
dt_regressor.fit(X_train, y_train)
# Make predictions
y_pred = dt_regressor.predict(X_test)
# Evaluate the model
mse3 = mean_squared_error(y_test, y_pred)
mae3 = mean_absolute_error(y_test, y_pred)
r23 = r2_score(y_test, y_pred)
explained_var3 = explained_variance_score(y_test, y_pred)
y_pred23 = y_pred
y_test23 = y_test
predictor3 = dt_regressor
mse4 = None
mae4 = None
r24 = None
explained_var4 = None
y_pred24 = None
y_test24 = None
predictor4 = None
def NN_Regression(ts):
global dataset, mse4, mae4, r24, explained_var4, target_name, y_test24, y_pred24, predictor4
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the Neural Network Regression model
nn_regressor = MLPRegressor(hidden_layer_sizes=(100, 50), max_iter=500)
nn_regressor.fit(X_train, y_train)
# Make predictions
y_pred = nn_regressor.predict(X_test)
# Evaluate the model
mse4 = mean_squared_error(y_test, y_pred)
mae4 = mean_absolute_error(y_test, y_pred)
r24 = r2_score(y_test, y_pred)
explained_var4 = explained_variance_score(y_test, y_pred)
y_pred24 = y_pred
y_test24 = y_test
predictor4 = nn_regressor
mse5 = None
mae5 = None
r25 = None
explained_var5 = None
y_pred25 = None
y_test25 = None
predictor5 = None
def RF_Regression(ts):
global mse5, mae5, r25, explained_var5, target_name, y_test25, y_pred25, predictor5
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the Neural Network Regression model
rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)
rf_regressor.fit(X_train, y_train)
# Make predictions
y_pred = rf_regressor.predict(X_test)
# Evaluate the model
mse5 = mean_squared_error(y_test, y_pred)
mae5 = mean_absolute_error(y_test, y_pred)
r25 = r2_score(y_test, y_pred)
explained_var5 = explained_variance_score(y_test, y_pred)
y_pred25 = y_pred
y_test25 = y_test
predictor5 = rf_regressor
mse6 = None
mae6 = None
r26 = None
explained_var6 = None
y_pred26 = None
y_test26 = None
predictor6 = None
def KNN_Regression(ts):
global mse6, mae6, r26, explained_var6, y_test26, y_pred26, predictor6
# Check for categorical columns
categorical_cols = dataset.select_dtypes(include=['object']).columns.tolist()
# Transform categorical columns using LabelEncoder
encoder = LabelEncoder()
for col in categorical_cols:
dataset[col] = encoder.fit_transform(dataset[col])
# Split data into features and target
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)
# Create and train the Neural Network Regression model
rf_regressor = KNeighborsRegressor(n_neighbors=5)
rf_regressor.fit(X_train, y_train)
# Make predictions
y_pred = rf_regressor.predict(X_test)
# Evaluate the model
mse6 = mean_squared_error(y_test, y_pred)
mae6 = mean_absolute_error(y_test, y_pred)
r26 = r2_score(y_test, y_pred)
explained_var6 = explained_variance_score(y_test, y_pred)
y_pred26 = y_pred
y_test26 = y_test
predictor6 = rf_regressor
def apply_ml_predictions():
ts = float(test_size.get())
print(ts)
# Appliquer les algorithmes de machine learning pour les problemes de regression
Linear_Regression(ts)
SV_Regression(ts)
DT_Regression(ts)
NN_Regression(ts)
RF_Regression(ts)
KNN_Regression(ts)
if dataset is not None:
# Text area 1 modification
text_area1.config(state=tk.NORMAL) # Set state to normal to modify
text_area1.delete(1.0, tk.END) # Clear previous content
text_area1.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse1}\n\n")
text_area1.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae1}\n\n")
text_area1.insert(tk.END, f"\n\n\t\tR-squared (R²): {r21}\n\n")
text_area1.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var1}\n\n")
text_area1.config(state=tk.DISABLED)
# Text area 2 modification
text_area2.config(state=tk.NORMAL) # Set state to normal to modify
text_area2.delete(1.0, tk.END) # Clear previous content
text_area2.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse2}\n\n")
text_area2.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae2}\n\n")
text_area2.insert(tk.END, f"\n\n\t\tR-squared (R²): {r22}\n\n")
text_area2.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var2}\n\n")
text_area2.config(state=tk.DISABLED)
# Text area 3 modification
text_area3.config(state=tk.NORMAL) # Set state to normal to modify
text_area3.delete(1.0, tk.END) # Clear previous content
text_area3.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse3}\n\n")
text_area3.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae3}\n\n")
text_area3.insert(tk.END, f"\n\n\t\tR-squared (R²): {r23}\n\n")
text_area3.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var3}\n\n")
text_area3.config(state=tk.DISABLED)
# Text area 4 modification
text_area4.config(state=tk.NORMAL) # Set state to normal to modify
text_area4.delete(1.0, tk.END) # Clear previous content
text_area4.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse4}\n\n")
text_area4.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae4}\n\n")
text_area4.insert(tk.END, f"\n\n\t\tR-squared (R²): {r24}\n\n")
text_area4.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var4}\n\n")
text_area4.config(state=tk.DISABLED)
# Text area 5 modification
text_area5.config(state=tk.NORMAL) # Set state to normal to modify
text_area5.delete(1.0, tk.END) # Clear previous content
text_area5.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse5}\n\n")
text_area5.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae5}\n\n")
text_area5.insert(tk.END, f"\n\n\t\tR-squared (R²): {r25}\n\n")
text_area5.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var5}\n\n")
text_area5.config(state=tk.DISABLED)
# Text area 5 modification
text_area6.config(state=tk.NORMAL) # Set state to normal to modify
text_area6.delete(1.0, tk.END) # Clear previous content
text_area6.insert(tk.END, f"\n\n\t\tMean Squared Error (MSE): {mse6}\n\n")
text_area6.insert(tk.END, f"\n\n\t\tMean Absolute Error (MAE): {mae6}\n\n")
text_area6.insert(tk.END, f"\n\n\t\tR-squared (R²): {r26}\n\n")
text_area6.insert(tk.END, f"\n\n\t\tExplained Variance Score: {explained_var6}\n\n")
text_area6.config(state=tk.DISABLED)
else:
CTkMessagebox(title="Error",
message="No Data, Please import a dataset first.",
icon="cancel",
option_1="Ok")
classifier = None
def visualise_classification_result():
global classifier
model = chosed_model.get()
if model == 'Native Bayes':
y_pred = y_pred1
y_test = y_test1
classifier = classifier1
elif model == 'Decision Tree':
y_pred = y_pred3
y_test = y_test3
classifier = classifier3
elif model == 'Random Forest Classifier':
y_pred = y_pred2
y_test = y_test2
classifier = classifier2
elif model == 'K-NN Classifier':
y_pred = y_pred4
y_test = y_test4
classifier = classifier4
elif model == 'SVM Classifier':
y_pred = y_pred5
y_test = y_test5
classifier = classifier5
elif model == 'Neural Network Classifier':
y_pred = y_pred6
y_test = y_test6
classifier = classifier6
X = dataset.drop(target_name, axis=1)
y = dataset[target_name]