-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml_models.py
More file actions
1660 lines (1372 loc) · 76.5 KB
/
ml_models.py
File metadata and controls
1660 lines (1372 loc) · 76.5 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
# ml_models.py
import datetime
import inspect # For checking model class parameter signatures
import json
import os
import pickle
import threading
import time
from functools import lru_cache
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import multiprocessing
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
# Scikit-learn imports
from sklearn.cluster import KMeans
from sklearn.ensemble import (BaggingClassifier, BaggingRegressor,
RandomForestClassifier, RandomForestRegressor,
StackingClassifier, StackingRegressor,
VotingClassifier, VotingRegressor)
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import (accuracy_score, classification_report,
confusion_matrix, explained_variance_score,
f1_score, mean_absolute_error, mean_squared_error,
precision_score, r2_score, recall_score,
roc_auc_score)
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
# Directory for saving models
MODELS_DIR = "ml_models"
os.makedirs(MODELS_DIR, exist_ok=True)
# Model Caching System
_MODEL_CACHE: Dict[str, Tuple[Any, Dict[str, Any], Dict[str, Any]]] = {} # Model cache dictionary
_MODEL_CACHE_LOCK = threading.RLock() # Cache lock
_MODEL_CACHE_MAX_SIZE = 10 # Maximum number of models to cache
_MODEL_CACHE_ACCESS_TIMES: Dict[str, float] = {} # Records last access time for each model
# Model mapping for easy lookup by name
MODEL_TYPES = {
# Regression Models
"linear_regression": LinearRegression,
"random_forest_regressor": RandomForestRegressor,
# Classification Models
"logistic_regression": LogisticRegression,
"decision_tree": DecisionTreeClassifier,
"random_forest_classifier": RandomForestClassifier,
"knn_classifier": KNeighborsClassifier,
"svm_classifier": SVC,
"naive_bayes": MultinomialNB,
# Clustering Models
"kmeans": KMeans,
# Ensemble Model Types
"voting_classifier": VotingClassifier,
"voting_regressor": VotingRegressor,
"stacking_classifier": StackingClassifier,
"stacking_regressor": StackingRegressor,
"bagging_classifier": BaggingClassifier,
"bagging_regressor": BaggingRegressor
}
# Model categories for frontend display and selection
MODEL_CATEGORIES = {
"regression": ["linear_regression", "random_forest_regressor"],
"classification": [
"logistic_regression", "knn_classifier", "decision_tree",
"svm_classifier", "naive_bayes", "random_forest_classifier"
],
"clustering": ["kmeans"]
}
# Detailed model information including icons and descriptions
MODEL_DETAILS = {
"linear_regression": {
"display_name": "Linear Regression Model",
"icon_class": "fa-chart-line",
"description": "A basic statistical model for predicting continuous variables. "
"It establishes a linear relationship between independent and dependent "
"variables, finding the best-fitting line. Suitable for simple numerical prediction tasks."
},
"logistic_regression": {
"display_name": "Logistic Regression Model",
"icon_class": "fa-code-branch",
"description": "A statistical model for binary classification problems. It converts "
"the output of a linear model into probability values using the Sigmoid function. "
"It is computationally efficient, easy to implement, and suitable for linearly separable classification problems."
},
"knn_classifier": {
"display_name": "K-Nearest Neighbors (KNN) Prediction Model",
"icon_class": "fa-project-diagram",
"description": "An instance-based learning method that classifies or predicts by "
"calculating the distance between a new sample and all samples in the training set, "
"selecting the K nearest neighbors for voting or averaging."
},
"decision_tree": {
"display_name": "Decision Tree",
"icon_class": "fa-sitemap",
"description": "A tree-structured classification model that divides data into different "
"categories through a series of conditional judgments. It is intuitive, highly interpretable, "
"can handle non-linear relationships, but is prone to overfitting."
},
"svm_classifier": {
"display_name": "Support Vector Machine (SVM) Model",
"icon_class": "fa-vector-square",
"description": "A powerful classification algorithm that distinguishes different classes "
"of data points by finding an optimal hyperplane. It performs well in high-dimensional spaces, "
"can handle non-linear problems using kernel functions, and is suitable for small, complex datasets."
},
"naive_bayes": {
"display_name": "Naive Bayes Classifier",
"icon_class": "fa-percentage",
"description": "A probabilistic classifier based on Bayes' theorem, assuming features are "
"mutually independent. It trains quickly, requires less training data, is particularly "
"suited for text classification and multi-class problems, but may not perform well on "
"data with strong feature correlations."
},
"kmeans": {
"display_name": "K-Means Model",
"icon_class": "fa-object-group",
"description": "A common clustering algorithm that partitions data points into K clusters "
"through iterative optimization. It is simple to implement, computationally efficient, "
"suitable for large-scale unsupervised learning, but is sensitive to initial cluster centers "
"and struggles with non-spherical clusters."
}
# Add details for RandomForest and ensemble models if they are user-selectable directly
}
# Default model parameters
DEFAULT_MODEL_PARAMS = {
"linear_regression": {},
"logistic_regression": {"max_iter": 1000, "C": 1.0, "solver": "liblinear"}, # Added solver for default
"decision_tree": {"max_depth": 5, "random_state": 42},
"random_forest_classifier": {"n_estimators": 100, "max_depth": 5, "random_state": 42},
"random_forest_regressor": {"n_estimators": 100, "max_depth": 5, "random_state": 42},
"knn_classifier": {"n_neighbors": 5},
"svm_classifier": {"C": 1.0, "kernel": "rbf", "probability": True, "random_state": 42}, # Added probability for consistency
"naive_bayes": {"alpha": 1.0},
"kmeans": {"n_clusters": 3, "random_state": 42, "n_init": "auto"} # Set n_init explicitly
}
def preprocess_data(
data: pd.DataFrame,
target_column: str,
categorical_columns: Optional[List[str]] = None,
numerical_columns: Optional[List[str]] = None,
test_size: float = 0.2,
scale_data: bool = True,
random_state: int = 42
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]:
"""
Preprocesses data for machine learning model training.
Args:
data: Input DataFrame.
target_column: Name of the target column.
categorical_columns: List of categorical feature names for encoding.
numerical_columns: List of numerical feature names for scaling.
test_size: Proportion of the dataset to include in the test split.
scale_data: Whether to scale numerical features.
random_state: Random seed for reproducibility.
Returns:
A tuple containing: X_train, X_test, y_train, y_test, preprocessors dictionary.
"""
df = data.copy()
preprocessors: Dict[str, Any] = {'label_encoders': {}, 'scaler': None}
# Handle categorical features
if categorical_columns:
for col in categorical_columns:
if col in df.columns and col != target_column: # Ensure not to encode target here
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
preprocessors['label_encoders'][col] = le
if target_column not in df.columns:
raise ValueError(f"Target column '{target_column}' not found in data.")
# Encode target column if it's categorical (object or many unique numericals)
if df[target_column].dtype == 'object' or \
(pd.api.types.is_numeric_dtype(df[target_column]) and df[target_column].nunique() < 0.1 * len(df[target_column])): # Heuristic for categorical numeric
le_target = LabelEncoder()
df[target_column] = le_target.fit_transform(df[target_column].astype(str))
preprocessors['label_encoders'][target_column] = le_target # Store target encoder as well
y = df[target_column].values
X_df = df.drop(columns=[target_column])
# Identify feature columns if not fully specified
if numerical_columns is None and categorical_columns is None:
numerical_columns = X_df.select_dtypes(include=np.number).columns.tolist()
categorical_columns = X_df.select_dtypes(exclude=np.number).columns.tolist()
elif numerical_columns is None:
numerical_columns = [col for col in X_df.columns if col not in (categorical_columns or [])]
elif categorical_columns is None:
categorical_columns = [col for col in X_df.columns if col not in (numerical_columns or [])]
# Ensure all identified columns exist in X_df
all_feature_cols = (numerical_columns or []) + (categorical_columns or [])
X = X_df[[col for col in all_feature_cols if col in X_df.columns]]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=random_state, stratify=(y if df[target_column].nunique() > 1 else None)
)
# Scale numerical features
if scale_data and numerical_columns:
scaler = StandardScaler()
# Filter numerical_columns to only those present in X_train (after split and potential column drops)
numerical_cols_in_X_train = [col for col in numerical_columns if col in X_train.columns]
if numerical_cols_in_X_train:
X_train[numerical_cols_in_X_train] = scaler.fit_transform(X_train[numerical_cols_in_X_train])
X_test[numerical_cols_in_X_train] = scaler.transform(X_test[numerical_cols_in_X_train])
preprocessors['scaler'] = scaler
preprocessors['scaled_numerical_columns'] = numerical_cols_in_X_train
return X_train.values, X_test.values, y_train, y_test, preprocessors
def train_model(
model_type: str,
data: Union[pd.DataFrame, str],
target_column: str,
model_name: Optional[str] = None,
categorical_columns: Optional[List[str]] = None,
numerical_columns: Optional[List[str]] = None,
model_params: Optional[Dict[str, Any]] = None,
test_size: float = 0.2,
random_state: int = 42
) -> Dict[str, Any]:
"""
Trains a machine learning model and saves it.
Args:
model_type: Model type (e.g., "linear_regression").
data: DataFrame or path to CSV/Excel file.
target_column: Name of the target variable column.
model_name: Name to save the model. Auto-generated if None.
categorical_columns: List of categorical feature names.
numerical_columns: List of numerical feature names.
model_params: Dictionary of model parameters.
test_size: Proportion for the test set split.
random_state: Random seed for reproducibility.
Returns:
Dictionary containing model information.
"""
if isinstance(data, str):
if data.lower().endswith('.csv'):
df = pd.read_csv(data)
elif data.lower().endswith(('.xlsx', '.xls')):
df = pd.read_excel(data)
else:
raise ValueError(f"Unsupported file format: {data}. Only CSV and Excel are supported.")
if len(df) > 10000 or df.memory_usage(deep=True).sum() > 100 * 1024 * 1024: # 10k rows or 100MB
df = optimize_dataframe_memory(df)
elif isinstance(data, pd.DataFrame):
df = data.copy()
else:
raise TypeError("Data must be a pandas DataFrame or a file path string.")
if model_type not in MODEL_TYPES:
raise ValueError(f"Invalid model type: {model_type}. Valid types: {list(MODEL_TYPES.keys())}")
# Auto-identify column types if not specified
if categorical_columns is None and numerical_columns is None:
temp_X = df.drop(columns=[target_column], errors='ignore')
numerical_columns = temp_X.select_dtypes(include=np.number).columns.tolist()
categorical_columns = temp_X.select_dtypes(exclude=np.number).columns.tolist()
print(f"Auto-identified numerical columns: {numerical_columns}")
print(f"Auto-identified categorical columns: {categorical_columns}")
X_train, X_test, y_train, y_test, preprocessors = preprocess_data(
df, target_column, categorical_columns, numerical_columns, test_size, random_state=random_state
)
current_model_params = DEFAULT_MODEL_PARAMS.get(model_type, {}).copy()
if model_params: # User-provided params override defaults
current_model_params.update(model_params)
# Add random_state to model params if model supports it and it's not already set
model_class = MODEL_TYPES[model_type]
model_signature = inspect.signature(model_class.__init__)
if 'random_state' in model_signature.parameters and 'random_state' not in current_model_params:
current_model_params['random_state'] = random_state
model = model_class(**current_model_params)
model.fit(X_train, y_train)
metrics = evaluate_model(model, X_test, y_test, model_type)
if model_name is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
model_name = f"{model_type}_{timestamp}"
metadata = {
"model_name": model_name, # Ensure model_name is part of metadata
"model_type": model_type,
"target_column": target_column,
"categorical_columns": categorical_columns,
"numerical_columns": numerical_columns, # Store identified numerical columns
"scaled_numerical_columns": preprocessors.get('scaled_numerical_columns'), # Store actually scaled columns
"metrics": metrics,
"model_params": current_model_params, # Store used parameters
"created_at": datetime.datetime.now().isoformat(),
"data_shape": df.shape,
"data_columns": df.columns.tolist(),
"feature_names_in": list(X.columns) if isinstance(X, pd.DataFrame) else None # Store feature names if X was DataFrame
}
model_path = os.path.join(MODELS_DIR, f"{model_name}.pkl")
with open(model_path, "wb") as f:
pickle.dump((model, preprocessors, metadata), f)
print(f"Model saved to: {model_path}")
return {
"model_name": model_name,
"model_type": model_type,
"metrics": metrics,
"feature_importance": getattr(model, "feature_importances_", None) # Keep this for quick access if needed
}
def load_model(model_name: str) -> Tuple[Any, Dict[str, Any], Dict[str, Any]]:
"""
Loads a machine learning model, its preprocessors, and metadata from a file.
Uses an LRU cache for performance optimization.
Returns:
A tuple: (model_object, preprocessors_dict, metadata_dict).
"""
model_path = os.path.join(MODELS_DIR, f"{model_name}.pkl")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model file not found: {model_path}")
file_mtime = os.path.getmtime(model_path)
cache_key = f"{model_name}_{file_mtime}"
with _MODEL_CACHE_LOCK:
if cache_key in _MODEL_CACHE:
_MODEL_CACHE_ACCESS_TIMES[cache_key] = time.time()
print(f"Loading model {model_name} from cache.")
return _MODEL_CACHE[cache_key]
print(f"Loading model {model_name} from file: {model_path}")
start_time = time.time()
try:
with open(model_path, "rb") as f:
loaded_data = pickle.load(f)
if isinstance(loaded_data, tuple) and len(loaded_data) == 3:
model, preprocessors, metadata = loaded_data
elif isinstance(loaded_data, tuple) and len(loaded_data) == 2: # Legacy format
model, preprocessors = loaded_data
metadata = {} # Create empty metadata for legacy models
print(f"Warning: Model {model_name} loaded in legacy format (no metadata found in .pkl).")
else: # Assume it's just the model object for very old formats
model = loaded_data
preprocessors = {}
metadata = {}
print(f"Warning: Model {model_name} loaded in very old format (only model object found).")
load_time = time.time() - start_time
print(f"Model {model_name} loaded in {load_time:.4f} seconds.")
result = (model, preprocessors, metadata)
if len(_MODEL_CACHE) >= _MODEL_CACHE_MAX_SIZE:
_clean_model_cache()
_MODEL_CACHE[cache_key] = result
_MODEL_CACHE_ACCESS_TIMES[cache_key] = time.time()
return result
except Exception as e:
print(f"Error loading model {model_name}: {str(e)}")
raise
def _clean_model_cache():
"""Cleans the model cache by removing the least recently used item."""
if not _MODEL_CACHE:
return
# Sort by access time (oldest first)
oldest_key = min(_MODEL_CACHE_ACCESS_TIMES, key=_MODEL_CACHE_ACCESS_TIMES.get)
_MODEL_CACHE.pop(oldest_key, None)
_MODEL_CACHE_ACCESS_TIMES.pop(oldest_key, None)
print(f"Removed least recently used model from cache: {oldest_key.split('_')[0]}")
def clear_model_cache():
"""Clears the entire model cache."""
with _MODEL_CACHE_LOCK:
_MODEL_CACHE.clear()
_MODEL_CACHE_ACCESS_TIMES.clear()
print("Model cache cleared.")
def predict(
model_name: str,
input_data: Union[pd.DataFrame, Dict[str, Any], List[Dict[str, Any]]],
) -> Dict[str, Any]: # Removed target_column as it's not used for prediction input
"""
Makes predictions using a saved model.
Args:
model_name: Name of the model.
input_data: Input data (DataFrame, single dict, or list of dicts).
Returns:
Dictionary containing predictions and related information.
"""
if isinstance(input_data, dict):
input_df = pd.DataFrame([input_data])
elif isinstance(input_data, list):
input_df = pd.DataFrame(input_data)
elif isinstance(input_data, pd.DataFrame):
input_df = input_data.copy()
else:
raise TypeError("input_data must be a pandas DataFrame, a dictionary, or a list of dictionaries.")
model, preprocessors, metadata = load_model(model_name)
# Use feature names from metadata if available, falling back to model's if any
feature_names_in = metadata.get("feature_names_in", None)
if feature_names_in is None and hasattr(model, 'feature_names_in_'):
feature_names_in = model.feature_names_in_
# Ensure input_df has the correct columns in the correct order
if feature_names_in is not None:
missing_cols = set(feature_names_in) - set(input_df.columns)
if missing_cols:
raise ValueError(f"Input data is missing columns: {missing_cols}")
input_df_processed = input_df[feature_names_in].copy() # Reorder/select columns
else:
# If no feature_names_in, assume input_df is already correctly ordered/featured
# This might be risky if preprocessors rely on specific column names/order
print("Warning: 'feature_names_in' not found in model metadata or model object. Assuming input data is correctly ordered.")
input_df_processed = input_df.copy()
# Apply preprocessing transformations
if 'label_encoders' in preprocessors:
for col, encoder in preprocessors['label_encoders'].items():
if col in input_df_processed.columns and col != metadata.get("target_column"): # Don't encode target if present
input_df_processed[col] = input_df_processed[col].astype(str)
# Handle unseen labels during transform
input_df_processed[col] = input_df_processed[col].apply(
lambda x: encoder.transform([x])[0] if x in encoder.classes_ else -1 # Or handle as NaN / specific category
)
if (input_df_processed[col] == -1).any():
print(f"Warning: Column '{col}' contained unseen labels, encoded as -1.")
if 'scaler' in preprocessors and preprocessors['scaler'] is not None:
scaled_num_cols = metadata.get('scaled_numerical_columns', []) # Use columns that were actually scaled
# Ensure only existing columns are selected for scaling
cols_to_scale = [col for col in scaled_num_cols if col in input_df_processed.columns]
if cols_to_scale:
input_df_processed[cols_to_scale] = preprocessors['scaler'].transform(input_df_processed[cols_to_scale])
X_predict = input_df_processed.values
predictions = model.predict(X_predict)
result = {
"model_name": model_name,
"predictions": predictions.tolist(),
}
if hasattr(model, "predict_proba"):
try:
probabilities = model.predict_proba(X_predict)
# Format probabilities based on number of classes
if probabilities.shape[1] == 2: # Binary classification
result["probabilities"] = probabilities[:, 1].tolist() # Prob of positive class
else: # Multiclass
# Return list of probability arrays, or dict mapping class name to prob
if hasattr(preprocessors.get('label_encoders',{}).get(metadata.get("target_column")), 'classes_'):
classes = preprocessors['label_encoders'][metadata.get("target_column")].classes_
result["probabilities"] = [{cls_name: prob for cls_name, prob in zip(classes, prob_array)} for prob_array in probabilities]
else:
result["probabilities"] = probabilities.tolist()
except Exception as e_proba:
print(f"Could not get probabilities: {e_proba}")
return result
def list_available_models() -> List[Dict[str, Any]]:
"""
Lists all available models, returning JSON-serializable metadata.
"""
models_metadata = []
if not os.path.exists(MODELS_DIR):
logger.warning(f"Models directory '{MODELS_DIR}' not found when listing models.")
return []
for filename in os.listdir(MODELS_DIR):
if filename.endswith(".pkl"):
model_name = os.path.splitext(filename)[0]
try:
_, _, metadata = load_model(model_name) # Load to get metadata
model_type = metadata.get("model_type", "unknown")
detail_info = MODEL_DETAILS.get(model_type, {})
model_info = {
"name": model_name,
"type": model_type,
"path": os.path.join(MODELS_DIR, filename),
"params": metadata.get("model_params", {}), # Already stringified if needed
"display_name": detail_info.get("display_name", model_name.replace("_", " ").title()),
"icon_class": detail_info.get("icon_class", "fa-brain"), # Default icon
"description": detail_info.get("description", f"A {model_type} model."),
"created_at": metadata.get("created_at"),
"internal_name": model_name, # For frontend data-model-name
"target_column": metadata.get("target_column"),
"feature_columns": metadata.get("feature_columns_in", metadata.get("categorical_columns", []) + metadata.get("numerical_columns", [])), # Prefer feature_names_in if available
"metrics": metadata.get("metrics")
}
# Ensure all values are serializable (should mostly be handled by metadata saving)
for key, value in list(model_info.items()):
if not isinstance(value, (str, int, float, bool, list, dict)) and value is not None:
model_info[key] = str(value)
models_metadata.append(model_info)
except Exception as e:
logger.error(f"Error loading or processing metadata for model {model_name}: {e}")
models_metadata.append({
"name": model_name, "type": "error",
"path": os.path.join(MODELS_DIR, filename), "error_message": str(e)
})
return models_metadata
def select_model_for_task(task_description: str) -> Optional[Dict[str, Any]]: # Return dict for more info
"""
Selects the most suitable model based on a task description.
(Simplified keyword-based implementation)
"""
available_models = list_available_models()
if not available_models:
return None
# English keywords
keywords_map = {
"regression": ["linear_regression", "random_forest_regressor"],
"predict numerical value": ["linear_regression", "random_forest_regressor"],
"price prediction": ["linear_regression", "random_forest_regressor"],
"sales forecast": ["linear_regression", "random_forest_regressor"],
"classification": ["logistic_regression", "decision_tree", "random_forest_classifier", "knn_classifier", "svm_classifier", "naive_bayes"],
"is it": ["logistic_regression", "decision_tree", "random_forest_classifier"], # "yes/no" type questions
"risk identification": ["logistic_regression", "random_forest_classifier"],
"credit risk": ["decision_tree", "random_forest_classifier"],
"health risk": ["logistic_regression", "random_forest_classifier"],
"customer churn": ["logistic_regression", "random_forest_classifier"]
}
task_desc_lower = task_description.lower()
preferred_model_types = []
for keyword, model_types_list in keywords_map.items():
if keyword in task_desc_lower:
preferred_model_types.extend(model_types_list)
recommendations = []
# First, check for preferred types
if preferred_model_types:
for model_info in available_models:
if model_info["type"] in preferred_model_types:
recommendations.append({
"model_type": model_info["type"],
"model_name": model_info["name"],
"confidence": 0.7, # Higher confidence for keyword match
"reason": f"Matches task description keyword related to '{model_info['type']}'."
})
# Add other available models with lower confidence if no strong match or to provide options
for model_info in available_models:
if not any(r['model_name'] == model_info['name'] for r in recommendations):
recommendations.append({
"model_type": model_info["type"],
"model_name": model_info["name"],
"confidence": 0.3, # Lower confidence for general models
"reason": "General purpose model, might be applicable."
})
if not recommendations: return None
# Sort by confidence (desc) then by name (asc)
recommendations.sort(key=lambda x: (-x['confidence'], x['model_name']))
return {
"recommended_model": recommendations[0]['model_name'] if recommendations else None, # Top recommendation
"recommendations": recommendations # List of all recommendations with scores
}
def save_model_with_version(
model: Any,
model_name: str,
preprocessors: Optional[Dict[str, Any]] = None,
metadata: Optional[Dict[str, Any]] = None,
version: Optional[str] = None
) -> Dict[str, Any]:
"""
Saves a model with version management.
Args:
model: The trained model object.
model_name: Base name for the model.
preprocessors: Dictionary of preprocessors used.
metadata: Model metadata.
version: Optional version string. If None, a timestamp-based version is generated.
Returns:
Dictionary containing version information.
"""
if version is None:
version = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
version_dir = os.path.join(MODELS_DIR, f"{model_name}_versions")
os.makedirs(version_dir, exist_ok=True)
versioned_model_name = f"{model_name}_v{version}"
model_path = os.path.join(version_dir, f"{versioned_model_name}.pkl")
with open(model_path, "wb") as f:
pickle.dump((model, preprocessors or {}, metadata or {}), f)
version_info = {
"model_name": model_name, "version": version,
"timestamp": datetime.datetime.now().isoformat(), "path": model_path,
}
if metadata: version_info.update(metadata)
version_info_path = os.path.join(version_dir, f"{versioned_model_name}_info.json")
with open(version_info_path, "w", encoding='utf-8') as f:
json.dump(version_info, f, indent=2, ensure_ascii=False)
return version_info
def list_model_versions(model_name: str) -> List[Dict[str, Any]]:
"""
Lists all versions of a given model.
Args:
model_name: Base name of the model.
Returns:
A list of version information dictionaries.
"""
version_dir = os.path.join(MODELS_DIR, f"{model_name}_versions")
if not os.path.exists(version_dir):
return []
versions = []
for filename in os.listdir(version_dir):
if filename.endswith("_info.json"): # Assuming info files denote versions
try:
with open(os.path.join(version_dir, filename), "r", encoding='utf-8') as f:
versions.append(json.load(f))
except json.JSONDecodeError:
logger.error(f"Could not decode JSON for version info file: {filename}")
except Exception as e:
logger.error(f"Error reading version info file {filename}: {e}")
versions.sort(key=lambda x: x.get("timestamp", ""), reverse=True) # Newest first
return versions
def load_model_version(model_name: str, version: str) -> Tuple[Any, Dict[str, Any], Dict[str, Any]]:
"""
Loads a specific version of a model.
Args:
model_name: Base name of the model.
version: Version string.
Returns:
A tuple: (model_object, preprocessors_dict, metadata_dict).
"""
version_dir = os.path.join(MODELS_DIR, f"{model_name}_versions")
model_path = os.path.join(version_dir, f"{model_name}_v{version}.pkl")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model version file not found: {model_path}")
with open(model_path, "rb") as f:
return pickle.load(f) # Assumes (model, preprocessors, metadata) structure
def create_ensemble_model(
base_models: List[Union[str, Tuple[str, Any]]], # Can be names or (name, model_obj)
ensemble_type: str = 'voting',
weights: Optional[List[float]] = None,
final_estimator: Optional[Any] = None, # For stacking
meta_features: bool = False, # For stacking, passthrough original features
save_name: Optional[str] = None
) -> Dict[str, Any]:
"""
Creates an ensemble model from base models.
Args:
base_models: List of base model names or (name, model_object) tuples.
ensemble_type: 'voting', 'stacking', or 'bagging'.
weights: Weights for voting ensemble.
final_estimator: Meta-learner for stacking.
meta_features: Whether to use original features in meta-learner for stacking.
save_name: Name to save the ensemble model.
Returns:
Dictionary with ensemble model info.
"""
loaded_base_models = []
is_classifier_list = [] # To check consistency
for item in base_models:
model_obj, model_name_str = None, None
if isinstance(item, tuple) and len(item) == 2:
model_name_str, model_obj = item
elif isinstance(item, str):
model_name_str = item
model_obj, _, _ = load_model(model_name_str) # Load preprocessors and metadata too
else:
raise ValueError(f"Invalid item in base_models: {item}. Must be name or (name, model_obj).")
if not isinstance(model_name_str, str): model_name_str = str(model_name_str) # Ensure name is string
loaded_base_models.append((model_name_str, model_obj))
is_classifier_list.append(hasattr(model_obj, "predict_proba"))
if not all(is_classifier_list) and not all(not x for x in is_classifier_list):
raise ValueError("All base models must be of the same type (all classifiers or all regressors).")
is_ensemble_classifier = is_classifier_list[0]
ensemble_model: Any = None
if ensemble_type == 'voting':
if is_ensemble_classifier:
ensemble_model = VotingClassifier(
estimators=loaded_base_models,
voting='soft' if all(hasattr(m[1], "predict_proba") for m in loaded_base_models) else 'hard',
weights=weights
)
else:
ensemble_model = VotingRegressor(estimators=loaded_base_models, weights=weights)
elif ensemble_type == 'stacking':
if is_ensemble_classifier:
ensemble_model = StackingClassifier(
estimators=loaded_base_models, final_estimator=final_estimator, passthrough=meta_features
)
else:
ensemble_model = StackingRegressor(
estimators=loaded_base_models, final_estimator=final_estimator, passthrough=meta_features
)
elif ensemble_type == 'bagging':
base_estimator_obj = loaded_base_models[0][1] # Bagging uses one type of base estimator
if is_ensemble_classifier:
ensemble_model = BaggingClassifier(base_estimator=base_estimator_obj)
else:
ensemble_model = BaggingRegressor(base_estimator=base_estimator_obj)
else:
raise ValueError(f"Unsupported ensemble type: {ensemble_type}")
ensemble_name = save_name or f"{ensemble_type}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
ensemble_metadata = {
'model_name': ensemble_name, 'ensemble_type': ensemble_type,
'base_model_names': [m[0] for m in loaded_base_models],
'is_classifier': is_ensemble_classifier, 'weights': weights,
'description': f"{ensemble_type.capitalize()} ensemble model based on {', '.join([m[0] for m in loaded_base_models])}."
}
# Ensemble preprocessors might be complex; for now, assume base models are used with their own or compatible preprocessed data.
# A true ensemble pipeline would need careful handling of preprocessing if base models require different steps.
ensemble_preprocessors = {'note': 'Preprocessing should be handled before feeding data to this ensemble or ensure base models use compatible preprocessed data.'}
model_path = os.path.join(MODELS_DIR, f"{ensemble_name}.pkl")
with open(model_path, "wb") as f:
pickle.dump((ensemble_model, ensemble_preprocessors, ensemble_metadata), f)
return {
'model_name': ensemble_name, 'model_path': model_path,
'model': ensemble_model, 'preprocessors': ensemble_preprocessors, 'metadata': ensemble_metadata
}
def auto_model_selection(
data_path: str,
target_column: str,
categorical_columns: Optional[List[str]] = None,
numerical_columns: Optional[List[str]] = None,
cv: int = 5,
metric: str = 'auto',
models_to_try: Optional[List[str]] = None,
random_state: int = 42
) -> Dict[str, Any]:
"""
Automatically selects the best model and parameters using GridSearchCV.
Args:
data_path: Path to the data file (CSV, Excel, JSON).
target_column: Name of the target column.
categorical_columns: List of categorical feature names.
numerical_columns: List of numerical feature names.
cv: Number of cross-validation folds.
metric: Evaluation metric ('auto', or specific scikit-learn scorer).
models_to_try: List of model types to try. None means try all suitable.
random_state: Random seed for reproducibility.
Returns:
Dictionary with the best model, its parameters, and performance.
"""
if data_path.lower().endswith('.csv'):
data = pd.read_csv(data_path, keep_default_na=False, na_values=['NaN', 'N/A', 'NA', 'nan', 'null'])
elif data_path.lower().endswith(('.xls', '.xlsx')):
data = pd.read_excel(data_path, keep_default_na=False, na_values=['NaN', 'N/A', 'NA', 'nan', 'null'])
elif data_path.lower().endswith('.json'): # Added JSON support
data = pd.read_json(data_path)
data = data.fillna('') # Simple fill for JSON, might need more sophisticated handling
else:
raise ValueError("Unsupported file format. Only CSV, Excel, and JSON are supported.")
if target_column not in data.columns:
raise ValueError(f"Target column '{target_column}' not in data. Available columns: {', '.join(data.columns)}")
if data.isna().any().any():
print("Warning: Missing values detected in data. Applying simple imputation (mean/mode).")
for col in data.columns:
if pd.api.types.is_numeric_dtype(data[col]):
data[col] = data[col].fillna(data[col].mean())
else:
data[col] = data[col].fillna(data[col].mode()[0] if not data[col].mode().empty else '')
X_train_np, X_test_np, y_train, y_test, preprocessors = preprocess_data(
data, target_column, categorical_columns, numerical_columns, random_state=random_state
)
unique_y_values = np.unique(y_train)
is_classification_task = len(unique_y_values) < 20 or not pd.api.types.is_numeric_dtype(y_train)
if models_to_try is None:
models_to_try = MODEL_CATEGORIES['classification'] if is_classification_task else MODEL_CATEGORIES['regression']
# Refined param_grids
param_grids = {
'logistic_regression': {'C': [0.1, 1.0, 10.0], 'solver': ['liblinear'], 'max_iter': [1000, 2000]},
'decision_tree': {'max_depth': [None, 5, 10, 15], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1,2,5]},
'random_forest_classifier': {'n_estimators': [50, 100, 150], 'max_depth': [None, 10, 20], 'min_samples_split': [2, 5]},
'random_forest_regressor': {'n_estimators': [50, 100, 150], 'max_depth': [None, 10, 20], 'min_samples_split': [2, 5]},
'knn_classifier': {'n_neighbors': [3, 5, 7, 9], 'weights': ['uniform', 'distance'], 'metric': ['euclidean', 'manhattan']},
'svm_classifier': {'C': [0.1, 1.0, 10.0], 'kernel': ['linear', 'rbf'], 'gamma': ['scale', 'auto']},
'linear_regression': {'fit_intercept': [True, False]}
}
scoring_metric = metric
if scoring_metric == 'auto':
scoring_metric = 'f1_weighted' if is_classification_task else 'neg_mean_squared_error'
best_cv_score = -float('inf')
best_model_instance = None
best_model_params = None
best_model_type_name = None
all_model_run_results = []
for model_type_key in models_to_try:
if model_type_key not in MODEL_TYPES:
print(f"Warning: Model type {model_type_key} is not supported. Skipping.")
continue
print(f"Training and optimizing {model_type_key} model...")
model_class_ref = MODEL_TYPES[model_type_key]
current_param_grid = param_grids.get(model_type_key, {})
try:
# Ensure n_jobs is set if model supports it
model_init_params = {}
model_signature = inspect.signature(model_class_ref.__init__)
if 'random_state' in model_signature.parameters: model_init_params['random_state'] = random_state
if 'n_jobs' in model_signature.parameters and model_type_key != 'svm_classifier': model_init_params['n_jobs'] = -1
grid_search_cv = GridSearchCV(
model_class_ref(**model_init_params), current_param_grid, cv=cv,
scoring=scoring_metric, n_jobs=(1 if model_type_key == 'svm_classifier' else -1) # SVM can be slow with n_jobs=-1 for some kernels
)
grid_search_cv.fit(X_train_np, y_train)
current_best_estimator = grid_search_cv.best_estimator_
y_pred_test = current_best_estimator.predict(X_test_np)
test_set_score = f1_score(y_test, y_pred_test, average='weighted') if is_classification_task \
else -mean_squared_error(y_test, y_pred_test) # Use negative MSE for regressors
current_model_metrics = evaluate_model(current_best_estimator, X_test_np, y_test, model_type_key)
all_model_run_results.append({
'model_type': model_type_key, 'best_params': grid_search_cv.best_params_,
'cv_score': grid_search_cv.best_score_, 'test_score': test_set_score, # Using consistent scoring direction
'metrics_on_test': current_model_metrics
})
if grid_search_cv.best_score_ > best_cv_score:
best_cv_score = grid_search_cv.best_score_
best_model_instance = current_best_estimator
best_model_params = grid_search_cv.best_params_
best_model_type_name = model_type_key
print(f" {model_type_key} optimization complete. CV Score: {grid_search_cv.best_score_:.4f}, Test Score: {test_set_score:.4f}")
except Exception as e_grid:
print(f"Error training {model_type_key}: {e_grid}")
if best_model_instance is None:
raise ValueError("No valid model could be trained successfully.")
final_model_name = f"automl_{best_model_type_name}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
final_metadata = {
'model_name': final_model_name, 'model_type': best_model_type_name,
'model_params': best_model_params, 'cv_score': best_cv_score,
'all_models_results': all_model_run_results, # Store results of all tried models
'is_classification': is_classification_task, 'metric_used': scoring_metric,
'created_by': 'auto_model_selection', 'random_state': random_state,
'target_column': target_column, 'categorical_columns': categorical_columns,
'numerical_columns': numerical_columns,
'scaled_numerical_columns': preprocessors.get('scaled_numerical_columns'),
'feature_names_in': list(X.columns) if isinstance(X, pd.DataFrame) else None
}
final_model_path = os.path.join(MODELS_DIR, f"{final_model_name}.pkl")
with open(final_model_path, "wb") as f:
pickle.dump((best_model_instance, preprocessors, final_metadata), f)
print(f"Best auto-selected model '{final_model_name}' saved to {final_model_path}")
return {
'model_name': final_model_name, 'model_type': best_model_type_name,
'model_path': final_model_path, 'model': best_model_instance,
'preprocessors': preprocessors, 'params': best_model_params,
'cv_score': best_cv_score, 'is_classification': is_classification_task,
'all_models_results': all_model_run_results
}
def explain_model_prediction(model_name: str, input_data: Union[Dict[str, Any], pd.DataFrame]) -> Dict[str, Any]:
"""
Explains a model's prediction (basic implementation).
Args:
model_name: Name of the model.
input_data: Input data (single dictionary or DataFrame for multiple).
Returns:
Explanation result, including feature importance and contributions.
"""
model, preprocessors, metadata = load_model(model_name)
if isinstance(input_data, dict):
input_df = pd.DataFrame([input_data])
elif isinstance(input_data, pd.DataFrame):
input_df = input_data.copy()
else:
raise TypeError("input_data must be a dictionary or pandas DataFrame.")
# Apply preprocessing (consistent with predict function)
input_df_processed = input_df.copy() # Start with a copy of the original input structure
# Use feature names from metadata if available
feature_names_in = metadata.get("feature_names_in", None)
if feature_names_in is None and hasattr(model, 'feature_names_in_'):
feature_names_in = model.feature_names_in_
if feature_names_in is not None:
# Ensure all necessary columns are present and in order
current_cols = input_df_processed.columns.tolist()
if not all(fn in current_cols for fn in feature_names_in):
raise ValueError(f"Input data missing required features. Expected: {feature_names_in}")
input_df_processed = input_df_processed[feature_names_in]
else:
print("Warning: Feature names for model input not found in metadata. Assuming input_data columns are correct and ordered.")
if 'label_encoders' in preprocessors:
for col, encoder in preprocessors['label_encoders'].items():
if col in input_df_processed.columns and col != metadata.get("target_column"):