iclltuning 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iclltuning/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .iclltuning import iclltuning
|
iclltuning/iclltuning.py
ADDED
|
@@ -0,0 +1,950 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import time
|
|
4
|
+
import warnings
|
|
5
|
+
import inspect
|
|
6
|
+
from scipy.cluster.hierarchy import linkage, fcluster
|
|
7
|
+
from scipy.spatial.distance import pdist
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from pandas.api.types import is_float_dtype, is_integer_dtype
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class iclltuning:
|
|
13
|
+
"""This is the class representation of this library. Invoke the methods of this class to perform hyperparameter tuning on the models fed to the Imbalanced Classification via Layered Learning (ICLL) model.
|
|
14
|
+
|
|
15
|
+
**Layer 1** follows the same definition as mentioned within the original paper: "Layer 1 (L1) denotes the event that the observation belongs to the Mixed or Pure Minority Group."
|
|
16
|
+
|
|
17
|
+
**Layer 2** follows the same definition as mentioned within the original paper: "Given that L1 occurs (i.e. observation belongs to the mixed or pure minority group), Layer 2 (L2) denotes the event that the observation belongs to the pure minority class."
|
|
18
|
+
|
|
19
|
+
:param model_l1: ML model to be fit on **Layer 1**. A model must be passed if you don't want hyperparameter tuning to be performed on **Layer 1** task.
|
|
20
|
+
|
|
21
|
+
|
|
|
22
|
+
| **Requirements:**
|
|
23
|
+
|
|
24
|
+
1. This model must have a callable :py:meth:`!fit` method.
|
|
25
|
+
2. This model must have a callable :py:meth:`!predict` in the case of hard classification or :py:meth:`!predict_proba` in the case of soft classification. Either one provided is fine.
|
|
26
|
+
|
|
27
|
+
|
|
|
28
|
+
| In the situation where both the model and cross-validation object are both provided, the model assigned to the cross-validation object will take precedence in the ICLL algorithm.
|
|
29
|
+
:type model_l1: object, **optional**
|
|
30
|
+
|
|
31
|
+
:param model_l2: ML model to be fit on **Layer 2**. A model must be passed if you don't want hyperparameter tuning to be performed on **Layer 2** task.
|
|
32
|
+
|
|
33
|
+
|
|
|
34
|
+
| **Requirements:**
|
|
35
|
+
|
|
36
|
+
1. This model must have a callable :py:meth:`!fit` method.
|
|
37
|
+
2. This model must have a callable :py:meth:`!predict` in the case of hard classification or :py:meth:`!predict_proba` in the case of soft classification. Either one provided is fine.
|
|
38
|
+
|
|
39
|
+
|
|
|
40
|
+
| In the situation where both the model and cross-validation object are both provided, the model assigned to the cross-validation object will take precedence in the ICLL algorithm.
|
|
41
|
+
:type model_l2: object, **optional**
|
|
42
|
+
|
|
43
|
+
:param cv_obj_l1: :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object to be fit on **Layer 1**.
|
|
44
|
+
|
|
45
|
+
.. note::
|
|
46
|
+
|
|
47
|
+
:py:attr:`refit` parameter of the :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object **must NOT be initialized with a value of False**. If it is instantiated a value of False, then the **ICLL model will NOT be trained**, and a :py:exc:`ValueError` will be raised instead.
|
|
48
|
+
|
|
49
|
+
:type cv_obj_l1: :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object, **optional**
|
|
50
|
+
|
|
51
|
+
:param cv_obj_l2: :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object to be fit on **Layer 2**.
|
|
52
|
+
|
|
53
|
+
.. note::
|
|
54
|
+
|
|
55
|
+
:py:attr:`refit` parameter of the :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object **must be NOT be initialized with a value of False**. If it is instantiated a value of False, then the **ICLL model will NOT be trained**, and a :py:exc:`ValueError` will be raised instead.
|
|
56
|
+
|
|
57
|
+
:type cv_obj_l2: :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object, **optional**
|
|
58
|
+
|
|
59
|
+
:param smote_obj_l1: SMOTE object to be passed for resampling on **Layer 1**.
|
|
60
|
+
:type smote_obj_l1: :py:class:`imblearn.over_sampling._smote.base.SMOTE`, **optional**
|
|
61
|
+
|
|
62
|
+
:param smote_obj_l2: SMOTE object to be passed for resampling on **Layer 2**.
|
|
63
|
+
:type smote_obj_l2: :py:class:`imblearn.over_sampling._smote.base.SMOTE`, **optional**
|
|
64
|
+
|
|
65
|
+
:param sample_wt_l1: Array of sample weights to be assigned for **Layer 1** training task.
|
|
66
|
+
|
|
67
|
+
.. note::
|
|
68
|
+
|
|
69
|
+
1. If :py:attr:`cv_obj_l1` parameter is passed, then hyperparameter tuning will be carried out with sample weights passed, and as a result, the best estimator as found out by :py:attr:`cv_obj_l1` will be trained with the provided sample weights. Note that both the :py:attr:`cv_obj_l1` object and its attached estimator must both have the :py:attr:`sample_weight` attribute for the :py:meth:`!fit` method. **Otherwise, hyperparameter tuning will be carried out without supplying the sample weights.**
|
|
70
|
+
2. If :py:attr:`cv_obj_l1` parameter is not passed, then :py:attr:`model_l1` parameter will be trained with sample weights of :py:attr:`sample_wt_l1`. Note that the estimator must have the :py:attr:`sample_weight` attribute for the :py:meth:`!fit` method. **Otherwise, estimator training will be carried out wihtout supplying the sample weights.**
|
|
71
|
+
3. If both parameters :py:attr:`smote_obj_l1` and :py:attr:`sample_wt_l1` are passed, then resampling will **NOT be performed on Layer 1**, and sample weights will be passed during model training/ hyperparameter tuning.
|
|
72
|
+
|
|
73
|
+
:type sample_wt_l1: numpy.ndarray/ List / Pandas Series, **optional**
|
|
74
|
+
|
|
75
|
+
:param sample_wt_l2: Array of sample weights to be assigned for **Layer 2** training task.
|
|
76
|
+
|
|
77
|
+
.. note::
|
|
78
|
+
|
|
79
|
+
1. If :py:attr:`cv_obj_l2` parameter is passed, then hyperparameter tuning will be carried out with sample weights passed, and as a result, the best estimator as found out by :py:attr:`cv_obj_l2` will be trained with the provided sample weights. Note that both the :py:attr:`cv_obj_l2` object and its attached estimator must both have the :py:attr:`sample_weight` attribute for the :py:meth:`!fit` method. **Otherwise, hyperparameter tuning will be carried out wihtout supplying the sample weights.**
|
|
80
|
+
2. If :py:attr:`cv_obj_l2` parameter is not passed, then :py:attr:`model_l2` parameter will be trained with sample weights of :py:attr:`sample_wt_l2`. Note that the estimator must have the :py:attr:`sample_weight` attribute for the :py:meth:`!fit` method. **Otherwise, estimator training will be carried out wihtout supplying the sample weights.**
|
|
81
|
+
3. If both parameters :py:attr:`smote_obj_l2` and :py:attr:`sample_wt_l2` are passed, then resampling will **NOT be performed on Layer 2**, and sample weights will be passed during model training/ hyperparameter tuning.
|
|
82
|
+
|
|
83
|
+
|
|
|
84
|
+
| **IMPORTANT**
|
|
85
|
+
|
|
86
|
+
In ICLL algorithm, **Layer 2** is trained to distinguish instances belonging to Mixed clusters from those belonging to Pure Minority clusters. Instances assigned to Pure Majority clusters are excluded from the training process in this layer. Consequently, only the sample weights corresponding to instances in Mixed or Pure Minority clusters are passed to the estimator or the :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object in **Layer 2**.
|
|
87
|
+
|
|
88
|
+
**WARNING**: Only use this parameter if you fully understand its effect on the training process.
|
|
89
|
+
|
|
90
|
+
:type sample_wt_l2: numpy.ndarray/ List / Pandas Series, **optional**
|
|
91
|
+
|
|
92
|
+
:param custom_distance_threshold: Provide a value for this parameter if you want to override the original implementation of the computation of distance threshold (flat clusters are obtained at a threshold of the log-transformed intra-cluster distance of **µ + σ**)
|
|
93
|
+
:type custom_distance_threshold: float, **optional**
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
def __init__(self,
|
|
97
|
+
model_l1=None,
|
|
98
|
+
model_l2=None,
|
|
99
|
+
cv_obj_l1=None,
|
|
100
|
+
cv_obj_l2=None,
|
|
101
|
+
smote_obj_l1=None,
|
|
102
|
+
smote_obj_l2=None,
|
|
103
|
+
sample_wt_l1=None,
|
|
104
|
+
sample_wt_l2=None,
|
|
105
|
+
custom_distance_threshold=None
|
|
106
|
+
):
|
|
107
|
+
"""Constructor of the class iclltuning
|
|
108
|
+
"""
|
|
109
|
+
self.__model_l1 = model_l1
|
|
110
|
+
self.__model_l2 = model_l2
|
|
111
|
+
|
|
112
|
+
self.__cv_obj_l1 = cv_obj_l1
|
|
113
|
+
self.__cv_obj_l2 = cv_obj_l2
|
|
114
|
+
|
|
115
|
+
self.__smote_obj_l1 = smote_obj_l1
|
|
116
|
+
self.__smote_obj_l2 = smote_obj_l2
|
|
117
|
+
|
|
118
|
+
self.__sample_wt_l1 = sample_wt_l1
|
|
119
|
+
self.__sample_wt_l2 = sample_wt_l2
|
|
120
|
+
|
|
121
|
+
self.__custom_distance_threshold = custom_distance_threshold
|
|
122
|
+
|
|
123
|
+
# Initialize model variables
|
|
124
|
+
self.__final_layer1_model = None
|
|
125
|
+
self.__final_layer2_model = None
|
|
126
|
+
|
|
127
|
+
# Initialize status of boolean variables
|
|
128
|
+
self.__cv_obj_l1_bool=False
|
|
129
|
+
self.__cv_obj_l2_bool=False
|
|
130
|
+
self.__apply_resample_l1=False
|
|
131
|
+
self.__apply_resample_l2=False
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def __layer_1_training(self,X,y,layer_wt):
|
|
135
|
+
"""Private class method to train the model assigned to Layer 1.
|
|
136
|
+
|
|
137
|
+
:param X: Independent variables data found by clustering assigned in Layer 1 for model training
|
|
138
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
139
|
+
|
|
140
|
+
:param y: Target variable. Target variable values must be in 1/0 format
|
|
141
|
+
:type y: Pandas Series or numpy.ndarray
|
|
142
|
+
|
|
143
|
+
:return: Returns None
|
|
144
|
+
:rtype: None
|
|
145
|
+
|
|
146
|
+
:meta private:
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
# Check whether a cross-validation object is provided
|
|
150
|
+
start=time.time()
|
|
151
|
+
|
|
152
|
+
if self.__cv_obj_l1_bool:
|
|
153
|
+
sig_cv = inspect.signature(self.__cv_obj_l1.fit)
|
|
154
|
+
sig_model = inspect.signature(self.__cv_obj_l1.estimator.fit)
|
|
155
|
+
|
|
156
|
+
if ("sample_weight" in sig_cv.parameters) and ("sample_weight" in sig_model.parameters) and (not self.__sample_wt_l1 is None):
|
|
157
|
+
self.__cv_obj_l1.fit(X,y,sample_weight=layer_wt)
|
|
158
|
+
|
|
159
|
+
else:
|
|
160
|
+
self.__cv_obj_l1.fit(X,y)
|
|
161
|
+
|
|
162
|
+
else:
|
|
163
|
+
# Check if the model has a parameter of 'sample_weight' present in fit()
|
|
164
|
+
sig = inspect.signature(self.__model_l1.fit)
|
|
165
|
+
|
|
166
|
+
if ("sample_weight" in sig.parameters) and (not self.__sample_wt_l1 is None):
|
|
167
|
+
self.__model_l1.fit(X,y,sample_weight=layer_wt)
|
|
168
|
+
|
|
169
|
+
else:
|
|
170
|
+
self.__model_l1.fit(X,y)
|
|
171
|
+
|
|
172
|
+
end=time.time()
|
|
173
|
+
|
|
174
|
+
self.__l1_time=(end-start)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def __layer_2_training(self,X,y,layer_wt):
|
|
178
|
+
"""Private class method to train the model assigned to Layer 2.
|
|
179
|
+
|
|
180
|
+
:param X: Independent variables data found by clustering assigned in Layer 2 for model training
|
|
181
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
182
|
+
|
|
183
|
+
:param y: Target variable. Target variable values must be in 1/0 format
|
|
184
|
+
:type y: Pandas Series or numpy.ndarray
|
|
185
|
+
|
|
186
|
+
:return: Returns None
|
|
187
|
+
:rtype: None
|
|
188
|
+
|
|
189
|
+
:meta private:
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
# Check whether a cross-validation object is provided
|
|
193
|
+
start=time.time()
|
|
194
|
+
|
|
195
|
+
if self.__cv_obj_l2_bool:
|
|
196
|
+
sig_cv = inspect.signature(self.__cv_obj_l2.fit)
|
|
197
|
+
sig_model = inspect.signature(self.__cv_obj_l2.estimator.fit)
|
|
198
|
+
|
|
199
|
+
if ("sample_weight" in sig_cv.parameters) and ("sample_weight" in sig_model.parameters) and (not self.__sample_wt_l2 is None):
|
|
200
|
+
self.__cv_obj_l2.fit(X,y,sample_weight=layer_wt)
|
|
201
|
+
|
|
202
|
+
else:
|
|
203
|
+
self.__cv_obj_l2.fit(X,y)
|
|
204
|
+
|
|
205
|
+
else:
|
|
206
|
+
# Check if the model has a parameter of 'sample_weight' present in fit()
|
|
207
|
+
sig = inspect.signature(self.__model_l2.fit)
|
|
208
|
+
|
|
209
|
+
if ("sample_weight" in sig.parameters) and (not self.__sample_wt_l2 is None):
|
|
210
|
+
self.__model_l2.fit(X,y,sample_weight=layer_wt)
|
|
211
|
+
|
|
212
|
+
else:
|
|
213
|
+
self.__model_l2.fit(X,y)
|
|
214
|
+
|
|
215
|
+
end=time.time()
|
|
216
|
+
|
|
217
|
+
self.__l2_time=(end-start)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def __three_way_grouping(cls, clusters, y):
|
|
222
|
+
"""This is a private class method which determines which cluster is an instance a part of (minority/ majority and mixed).
|
|
223
|
+
|
|
224
|
+
:param clusters: A nested list which contains instances belonging to which clusters as obtained by hierarchical clustering
|
|
225
|
+
:type clusters: list
|
|
226
|
+
|
|
227
|
+
:param y: Class label of instances
|
|
228
|
+
:type y: numpy.ndarray
|
|
229
|
+
|
|
230
|
+
:return c_mix_all_ind: Indices of the observations which belong to either the mixed or minority clusters
|
|
231
|
+
:rtype: numpy.ndarray
|
|
232
|
+
|
|
233
|
+
:return cluster_summary_dict: A dictionary which indicates count of observations which belong to majority/minority/mixed clusters.
|
|
234
|
+
:rtype: dict
|
|
235
|
+
|
|
236
|
+
:meta private:
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
# c_maj_list = list of clusters containing pure negative class instances (c_maj)
|
|
240
|
+
# c_min_list = list of clusters containing pure positive class instances (c_min)
|
|
241
|
+
# c_mix_list = list of clusters containing mix of positive and negative class instances (c_mix)
|
|
242
|
+
c_maj_list, c_min_list, c_mix_list = [], [], []
|
|
243
|
+
|
|
244
|
+
# Loop through individual clusters
|
|
245
|
+
for clst in clusters:
|
|
246
|
+
try:
|
|
247
|
+
# Get the corresponding target label of each instance in that cluster
|
|
248
|
+
y_clt = y[np.asarray(clst)]
|
|
249
|
+
|
|
250
|
+
# Get a dictionary with key as 0/1 and value as the count of instances belonging to 0/1
|
|
251
|
+
if len(Counter(y_clt)) == 1:
|
|
252
|
+
# Since dictionary length is 1, which means that the cluster is a c_maj or c_min cluster
|
|
253
|
+
# So, all elements must belong to only one class label, which is why it is sufficient enough to check the first element of the list y_clt
|
|
254
|
+
if y_clt[0] == 0:
|
|
255
|
+
c_maj_list.append(clst)
|
|
256
|
+
else:
|
|
257
|
+
c_min_list.append(clst)
|
|
258
|
+
|
|
259
|
+
# Dictionary length is 2, which means the cluster is c_mix
|
|
260
|
+
else:
|
|
261
|
+
c_mix_list.append(clst)
|
|
262
|
+
|
|
263
|
+
except ValueError:
|
|
264
|
+
raise ValueError('Error when creating three-way groups.')
|
|
265
|
+
|
|
266
|
+
cluster_summary_dict={
|
|
267
|
+
'MAJORITY_CLUSTER_COUNT':len(c_maj_list),
|
|
268
|
+
'MINORITY_CLUSTER_COUNT':len(c_min_list),
|
|
269
|
+
'MIXED_CLUSTER_COUNT':len(c_mix_list)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
# Create a 1-D array of the indices of all instances which belong to c_mix. np.concatenate() returns a 1-D flattened array, and np.sort() sorts the indices in ascending order
|
|
273
|
+
if len(c_mix_list) > 0:
|
|
274
|
+
c_mix_ind = np.sort(np.concatenate(c_mix_list))
|
|
275
|
+
else:
|
|
276
|
+
c_mix_ind = np.array([])
|
|
277
|
+
|
|
278
|
+
if len(c_min_list) > 0:
|
|
279
|
+
c_min_ind = np.sort(np.concatenate(c_min_list))
|
|
280
|
+
else:
|
|
281
|
+
c_min_ind = np.array([])
|
|
282
|
+
|
|
283
|
+
# Get the indices of the observations which belong to either the c_mix or c_min clusters
|
|
284
|
+
c_mix_all_ind = np.sort(np.concatenate([c_mix_ind,c_min_ind]))
|
|
285
|
+
|
|
286
|
+
return c_mix_all_ind,cluster_summary_dict
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@classmethod
|
|
290
|
+
def __clustering(cls, X, custom_distance_threshold):
|
|
291
|
+
"""
|
|
292
|
+
Perform agglomerative heirarchical clustering on the given data.
|
|
293
|
+
|
|
294
|
+
Calculation Notes:
|
|
295
|
+
pdist() calculates the pairwise euclidean distance between observations.
|
|
296
|
+
|
|
297
|
+
Let 'm' be the number of observations.
|
|
298
|
+
Since a distance matrix is usually a 2D m x m matrix, it is avoided and instead only the upper triangular matrix is stored, discarding all symmetric elements.
|
|
299
|
+
|
|
300
|
+
The length of the array will then be m*(m-1)/2.
|
|
301
|
+
|
|
302
|
+
:param X: Independent variables data on which agglomerative heirarchical clustering will be performed.
|
|
303
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
304
|
+
|
|
305
|
+
:param custom_distance_threshold: A user provided threshold to get the cut-off distance at which the final set of flat clusters would be formed.
|
|
306
|
+
:type custom_distance_threshold: float, **optional**
|
|
307
|
+
|
|
308
|
+
:return clusters: Clusters of indices of data observations
|
|
309
|
+
:rtype clusters: numpy.ndarray
|
|
310
|
+
|
|
311
|
+
:return original_distance: Log-transformed intra-cluster distance of µ + σ. This would be the cut-off for obtaining flat clsuters.
|
|
312
|
+
:rtype original_distance: float
|
|
313
|
+
|
|
314
|
+
:meta private:
|
|
315
|
+
"""
|
|
316
|
+
d = pdist(X) # PAIRWISE DISTANCE BETWEEN INSTANCES
|
|
317
|
+
|
|
318
|
+
Z = linkage(d, method='ward') # calculate the instances links for the agglomerative clustering
|
|
319
|
+
|
|
320
|
+
Z[:, 2] = np.log(1 + Z[:, 2])
|
|
321
|
+
sZ = np.std(Z[:, 2]) # standard deviation of the distance between each cluster linkage
|
|
322
|
+
mZ = np.mean(Z[:, 2]) # mean of the distance between each cluster linkage
|
|
323
|
+
|
|
324
|
+
original_distance= sZ+mZ
|
|
325
|
+
|
|
326
|
+
if pd.isna(custom_distance_threshold):
|
|
327
|
+
cut_off_distance = original_distance
|
|
328
|
+
else:
|
|
329
|
+
cut_off_distance=custom_distance_threshold
|
|
330
|
+
|
|
331
|
+
clustLabs = fcluster(Z, cut_off_distance,criterion='distance') # for the clusters using merger distance threshold as mZ+stds*sZ
|
|
332
|
+
|
|
333
|
+
#: 'clusters' variable is a list of list. The number of elements in the 'clusters' variable is equal to the number of clusters formed.
|
|
334
|
+
#: Each nested list houses the indices of the observation belonging to that particular cluster. Egs: Cluster 1 has observations whose indices are [3,7].
|
|
335
|
+
clusters = []
|
|
336
|
+
for lab in np.unique(clustLabs): # produce a clusters data structure to work with
|
|
337
|
+
clusters.append(np.where(clustLabs == lab)[0])
|
|
338
|
+
|
|
339
|
+
return clusters,original_distance
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def fit(self, X, y):
|
|
343
|
+
"""Fit the ICLL model on your dataset.
|
|
344
|
+
|
|
345
|
+
:param X: Independent variables data for model training
|
|
346
|
+
|
|
347
|
+
.. note::
|
|
348
|
+
|
|
349
|
+
Since the first step of ICLL model is to perform the agglomerative hierarchical clustering, it is expected that all elements of :py:attr:`X` will only contain **non-null integer or floating** data types. Failure to adhere to this will result in a :py:exc:`ValueError` being raised instead.
|
|
350
|
+
|
|
351
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
352
|
+
|
|
353
|
+
:param y: Target variable. Target variable values must be in 1/0 format
|
|
354
|
+
:type y: Pandas Series or numpy.ndarray
|
|
355
|
+
|
|
356
|
+
:return: Fitted estimator.
|
|
357
|
+
:rtype: Object
|
|
358
|
+
|
|
359
|
+
:meta public:
|
|
360
|
+
"""
|
|
361
|
+
# Set initial status of boolean variables
|
|
362
|
+
self.__dual_model=False
|
|
363
|
+
|
|
364
|
+
# Set initial values of core variables
|
|
365
|
+
self.__decisive_action = ""
|
|
366
|
+
|
|
367
|
+
self.__computed_distance = np.nan
|
|
368
|
+
self.__clustering_info_dict ={
|
|
369
|
+
'MAJORITY_CLUSTER_COUNT':np.nan,
|
|
370
|
+
'MINORITY_CLUSTER_COUNT':np.nan,
|
|
371
|
+
'MIXED_CLUSTER_COUNT':np.nan
|
|
372
|
+
}
|
|
373
|
+
self.__l1_time=np.nan
|
|
374
|
+
self.__l2_time=np.nan
|
|
375
|
+
|
|
376
|
+
self.__final_layer1_model = None
|
|
377
|
+
self.__final_layer2_model = None
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# Perform checks to ensure that the class object has been initialized with correct attribute datatypes
|
|
381
|
+
if not ((type(self.__cv_obj_l1).__name__ in ["GridSearchCV","RandomizedSearchCV"]) or pd.isna(self.__cv_obj_l1)):
|
|
382
|
+
raise ValueError("Invalid value for parameter 'cv_obj_l1'. This parameter only accepts an object from class 'GridSearchCV' or 'RandomizedSearchCV'. This parameter can also accept None if hyperparameter tuning on Layer 1 model is not desired.")
|
|
383
|
+
else:
|
|
384
|
+
if pd.isna(self.__cv_obj_l1):
|
|
385
|
+
pass
|
|
386
|
+
else:
|
|
387
|
+
self.__cv_obj_l1_bool=True
|
|
388
|
+
|
|
389
|
+
# Check if refit parameter is initialized with False
|
|
390
|
+
if self.__cv_obj_l1.refit is False:
|
|
391
|
+
raise ValueError("'refit' parameter in 'cv_obj_l1' MUST NOT be initialized with a value of False!")
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
if not ((type(self.__cv_obj_l2).__name__ in ["GridSearchCV","RandomizedSearchCV"]) or pd.isna(self.__cv_obj_l2)):
|
|
395
|
+
raise ValueError("Invalid value for parameter 'cv_obj_l2'. This parameter only accepts an object from class 'GridSearchCV' or 'RandomizedSearchCV'. This parameter can also accept None if hyperparameter tuning on Layer 2 model is not desired.")
|
|
396
|
+
else:
|
|
397
|
+
if pd.isna(self.__cv_obj_l2):
|
|
398
|
+
pass
|
|
399
|
+
else:
|
|
400
|
+
self.__cv_obj_l2_bool=True
|
|
401
|
+
|
|
402
|
+
# Check if refit parameter is initialized with False
|
|
403
|
+
if self.__cv_obj_l2.refit is False:
|
|
404
|
+
raise ValueError("'refit' parameter in 'cv_obj_l2' MUST NOT be initialized with a value of False!")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
if not ((hasattr(self.__model_l1, "fit") and callable(self.__model_l1.fit)) or pd.isna(self.__model_l1)):
|
|
409
|
+
raise ValueError("Model to be trained on Layer 1 does not have a callable fit(X,y) method")
|
|
410
|
+
else:
|
|
411
|
+
if (pd.isna(self.__model_l1) and (not self.__cv_obj_l1_bool)):
|
|
412
|
+
raise ValueError("Both parameters 'model_l1' and 'cv_obj_l1' for Layer 1 task are empty! Atleast one should be provided.")
|
|
413
|
+
else:
|
|
414
|
+
pass
|
|
415
|
+
|
|
416
|
+
if not ((hasattr(self.__model_l2, "fit") and callable(self.__model_l2.fit)) or pd.isna(self.__model_l2)):
|
|
417
|
+
raise ValueError("Model to be trained on Layer 2 does not have a callable fit(X,y) method")
|
|
418
|
+
else:
|
|
419
|
+
if (pd.isna(self.__model_l2) and (not self.__cv_obj_l2_bool)):
|
|
420
|
+
raise ValueError("Both parameters 'model_l2' and 'cv_obj_l2' for Layer 2 task are empty! Atleast one should be provided.")
|
|
421
|
+
else:
|
|
422
|
+
pass
|
|
423
|
+
|
|
424
|
+
if not ((type(self.__smote_obj_l1).__name__=="SMOTE") or pd.isna(self.__smote_obj_l1)):
|
|
425
|
+
raise ValueError("Resampling method for layer 1 does not belong to imblearn package -> SMOTE. This parameter can also accept None if resampling tuning on Layer 1 training data is not desired.")
|
|
426
|
+
else:
|
|
427
|
+
if pd.notna(self.__smote_obj_l1):
|
|
428
|
+
self.__apply_resample_l1=True
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
if not ((type(self.__smote_obj_l2).__name__=="SMOTE") or pd.isna(self.__smote_obj_l2)):
|
|
432
|
+
raise ValueError("Resampling method for layer 2 does not belong to imblearn package -> SMOTE. This parameter can also accept None if resampling tuning on Layer 2 training data is not desired.")
|
|
433
|
+
else:
|
|
434
|
+
if pd.notna(self.__smote_obj_l2):
|
|
435
|
+
self.__apply_resample_l2=True
|
|
436
|
+
|
|
437
|
+
if not (isinstance(self.__sample_wt_l1,(list,np.ndarray,pd.Series)) or (self.__sample_wt_l1 is None)):
|
|
438
|
+
raise ValueError("Parameter 'sample_wt_l1' is not a List/numpy.ndarray/Pandas Series data type. This parameter can also accept None if no sample weights are to be assigned during model training of Layer 1.")
|
|
439
|
+
else:
|
|
440
|
+
if (self.__sample_wt_l1 is None):
|
|
441
|
+
pass
|
|
442
|
+
else:
|
|
443
|
+
self.__sample_wt_l1 = np.array(self.__sample_wt_l1)
|
|
444
|
+
|
|
445
|
+
if self.__sample_wt_l1.ndim != 1:
|
|
446
|
+
raise ValueError("Parameter 'sample_wt_l1' must be one-dimensional.")
|
|
447
|
+
else:
|
|
448
|
+
# Override resampling on Layer 1
|
|
449
|
+
self.__apply_resample_l1 = False
|
|
450
|
+
|
|
451
|
+
if not (isinstance(self.__sample_wt_l2,(list,np.ndarray,pd.Series)) or (self.__sample_wt_l2 is None)):
|
|
452
|
+
raise ValueError("Parameter 'sample_wt_l2' is not a List/numpy.ndarray/Pandas Series data type. This parameter can also accept None if no sample weights are to be assigned during model training of Layer 2.")
|
|
453
|
+
else:
|
|
454
|
+
if (self.__sample_wt_l2 is None):
|
|
455
|
+
pass
|
|
456
|
+
else:
|
|
457
|
+
self.__sample_wt_l2 = np.array(self.__sample_wt_l2)
|
|
458
|
+
|
|
459
|
+
if self.__sample_wt_l2.ndim != 1:
|
|
460
|
+
raise ValueError("Parameter 'sample_wt_l2' must be one-dimensional.")
|
|
461
|
+
else:
|
|
462
|
+
# Override resampling on Layer 2
|
|
463
|
+
self.__apply_resample_l2 = False
|
|
464
|
+
|
|
465
|
+
if not isinstance(X,(pd.DataFrame,np.ndarray)):
|
|
466
|
+
raise ValueError("Parameter 'X' is not a Pandas Dataframe or a numpy.ndarray datatype!")
|
|
467
|
+
|
|
468
|
+
if not isinstance(y,(pd.Series,np.ndarray)):
|
|
469
|
+
raise ValueError("Parameter 'y' is not a Pandas Series or a numpy.ndarray datatype!")
|
|
470
|
+
|
|
471
|
+
if not (isinstance(self.__custom_distance_threshold,(int,float)) or pd.isna(self.__custom_distance_threshold)):
|
|
472
|
+
raise ValueError("Parameter 'custom_distance_threshold' is not an integer or float datatype. This parameter can also accept None if the originally computed intra-cluster distance is to be retained.")
|
|
473
|
+
|
|
474
|
+
# Check if a negative / zero distance is passed
|
|
475
|
+
if pd.isna(self.__custom_distance_threshold):
|
|
476
|
+
pass
|
|
477
|
+
else:
|
|
478
|
+
if (self.__custom_distance_threshold<=0) or (not np.isfinite(self.__custom_distance_threshold)):
|
|
479
|
+
raise ValueError("Parameter 'custom_distance_threshold' must contain a positive, non-zero finite value!")
|
|
480
|
+
|
|
481
|
+
# Convert pandas series (if given) to numpy array
|
|
482
|
+
y = np.asarray(y)
|
|
483
|
+
|
|
484
|
+
if X.shape[0] != y.shape[0]:
|
|
485
|
+
raise ValueError(f"X and y must contain the same number of samples; got {X.shape[0]} samples in X and {y.shape[0]} in y.")
|
|
486
|
+
|
|
487
|
+
if X.ndim != 2 or X.shape[1] == 0:
|
|
488
|
+
raise ValueError("'X' must be two-dimensional and contain at least one feature!")
|
|
489
|
+
|
|
490
|
+
if X.shape[0] < 2:
|
|
491
|
+
raise ValueError("'X' must contain at least two samples!")
|
|
492
|
+
|
|
493
|
+
# Check if y contains more than one dimension.
|
|
494
|
+
if y.ndim != 1:
|
|
495
|
+
raise ValueError("Parameter 'y' must be one-dimensional.")
|
|
496
|
+
|
|
497
|
+
# Check if the pandas dataframe/ numpy array of X contains integer and floating datatypes only
|
|
498
|
+
if isinstance(X, pd.DataFrame):
|
|
499
|
+
# Check if all cells have integer or float values
|
|
500
|
+
if not all(is_integer_dtype(dtype) or is_float_dtype(dtype) for dtype in X.dtypes):
|
|
501
|
+
raise ValueError("All values in 'X' must have integer or float dtypes!")
|
|
502
|
+
|
|
503
|
+
# Check if 'X' only contains finite values
|
|
504
|
+
if not np.isfinite(X.values).all():
|
|
505
|
+
raise ValueError("'X' must not contain any missing or infinite values!")
|
|
506
|
+
|
|
507
|
+
else:
|
|
508
|
+
X = np.asarray(X)
|
|
509
|
+
if X.dtype.kind not in "iuf":
|
|
510
|
+
raise ValueError("All values in 'X' must have integer or float dtypes!")
|
|
511
|
+
|
|
512
|
+
# Check if 'X' only contains finite values
|
|
513
|
+
if not np.isfinite(X).all():
|
|
514
|
+
raise ValueError("'X' must not contain any missing or infinite values!")
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# Check if y contains only labels of 0 and 1.
|
|
518
|
+
if (not np.isin(y, [0, 1]).all() or not np.any(y == 0) or not np.any(y == 1)):
|
|
519
|
+
raise ValueError("Parameter 'y' must contain both binary class labels 0 and 1.")
|
|
520
|
+
|
|
521
|
+
if self.__sample_wt_l1 is None:
|
|
522
|
+
pass
|
|
523
|
+
else:
|
|
524
|
+
# If self.__sample_wt_l1 is passed, then check if the length is the same as the length of 'X'
|
|
525
|
+
if len(self.__sample_wt_l1)!=len(X):
|
|
526
|
+
raise ValueError(f"sample_wt_l1 and X must contain the same number of samples; got {X.shape[0]} samples in X and {len(self.__sample_wt_l1)} in sample_wt_l1.")
|
|
527
|
+
|
|
528
|
+
if self.__sample_wt_l2 is None:
|
|
529
|
+
pass
|
|
530
|
+
else:
|
|
531
|
+
# If self.__sample_wt_l2 is passed, then check if the length is the same as the length of 'X'
|
|
532
|
+
if len(self.__sample_wt_l2)!=len(X):
|
|
533
|
+
raise ValueError(f"sample_wt_l2 and X must contain the same number of samples; got {X.shape[0]} samples in X and {len(self.__sample_wt_l2)} in sample_wt_l2.")
|
|
534
|
+
|
|
535
|
+
# Perform clustering
|
|
536
|
+
self.__clusters, self.__computed_distance = self.__clustering(X,self.__custom_distance_threshold)
|
|
537
|
+
|
|
538
|
+
# Perform grouping of instances
|
|
539
|
+
self.__all_ind_arr, self.__clustering_info_dict = self.__three_way_grouping(self.__clusters, y)
|
|
540
|
+
|
|
541
|
+
# Case 1: The base case. All types of clusters are formed.
|
|
542
|
+
if (self.__clustering_info_dict['MAJORITY_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MIXED_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MINORITY_CLUSTER_COUNT']>0):
|
|
543
|
+
self.__decisive_action = 'C1'
|
|
544
|
+
|
|
545
|
+
# Case 2: No pure majority clusters are formed.
|
|
546
|
+
elif (self.__clustering_info_dict['MAJORITY_CLUSTER_COUNT']==0) and (self.__clustering_info_dict['MIXED_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MINORITY_CLUSTER_COUNT']>0):
|
|
547
|
+
self.__decisive_action = 'C2'
|
|
548
|
+
|
|
549
|
+
# Case 3: No mixed clusters are formed.
|
|
550
|
+
elif (self.__clustering_info_dict['MAJORITY_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MIXED_CLUSTER_COUNT']==0) and (self.__clustering_info_dict['MINORITY_CLUSTER_COUNT']>0):
|
|
551
|
+
self.__decisive_action = 'C3'
|
|
552
|
+
|
|
553
|
+
# Case 4: No pure minority clusters are formed
|
|
554
|
+
elif (self.__clustering_info_dict['MAJORITY_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MIXED_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MINORITY_CLUSTER_COUNT']==0):
|
|
555
|
+
self.__decisive_action = 'C4'
|
|
556
|
+
warnings.warn("No pure minority clusters was formed! ICLL model training will carry on as usual.")
|
|
557
|
+
|
|
558
|
+
# Case 5: Only mixed clusters are formed
|
|
559
|
+
elif (self.__clustering_info_dict['MAJORITY_CLUSTER_COUNT']==0) and (self.__clustering_info_dict['MIXED_CLUSTER_COUNT']>0) and (self.__clustering_info_dict['MINORITY_CLUSTER_COUNT']==0):
|
|
560
|
+
self.__decisive_action = 'C5'
|
|
561
|
+
|
|
562
|
+
# Case 6: Base case (will never happen)
|
|
563
|
+
else:
|
|
564
|
+
self.__decisive_action = 'C6'
|
|
565
|
+
|
|
566
|
+
# Raise warnings and stop ICLL model training if case 'C2' arises
|
|
567
|
+
if self.__decisive_action == 'C2':
|
|
568
|
+
warnings.warn(f"No pure majority clusters were formed! Try to instantiate ICLL again by providing a new distance threshold for parameter 'custom_distance_threshold'. The computed distance threshold is in this run is {self.__computed_distance}")
|
|
569
|
+
|
|
570
|
+
# Raise warnings and stop model training if case 'C3' arises
|
|
571
|
+
elif self.__decisive_action == 'C3':
|
|
572
|
+
warnings.warn("No mixed clusters were formed! Since heirarchical clustering was able to seperate both classes effectively, so the ICLL model approach for this predictive task is redundant.")
|
|
573
|
+
|
|
574
|
+
# Raise warnings and stop model training if case 'C5' arises
|
|
575
|
+
elif self.__decisive_action == 'C5':
|
|
576
|
+
warnings.warn("Only a mixed cluster was formed! ICLL model training will not carry on further.")
|
|
577
|
+
|
|
578
|
+
#This block will never trigger
|
|
579
|
+
elif self.__decisive_action == 'C6':
|
|
580
|
+
warnings.warn("only a single type of pure majority/ pure mixed/ pure minority cluster was formed! ICLL model training will not carry on further.")
|
|
581
|
+
|
|
582
|
+
# Continue with ICLL model training as usual
|
|
583
|
+
else:
|
|
584
|
+
|
|
585
|
+
# Since __all_ind_arr variable contains indices of observations belonging to either c_mix or c_min clusters, those observations are tagged as 1 for L1 predictive task
|
|
586
|
+
# The observations belonging to the majority class can get their label flipped from 0 to 1 if they belong to a c_mix cluster.
|
|
587
|
+
y_l1 = y.copy()
|
|
588
|
+
y_l1[self.__all_ind_arr] = 1
|
|
589
|
+
|
|
590
|
+
if not self.__apply_resample_l1:
|
|
591
|
+
self.__layer_1_training(X, y_l1,self.__sample_wt_l1)
|
|
592
|
+
|
|
593
|
+
else:
|
|
594
|
+
try:
|
|
595
|
+
X_L1, y_L1 = self.__smote_obj_l1.fit_resample(X, y_l1)
|
|
596
|
+
self.__layer_1_training(X_L1, y_L1,self.__sample_wt_l1)
|
|
597
|
+
|
|
598
|
+
except ValueError as e:
|
|
599
|
+
warnings.warn(f"Layer 1 SMOTE failed due to: ({e})\n Performing model fit of Layer 1 without resampling...",
|
|
600
|
+
RuntimeWarning,
|
|
601
|
+
stacklevel=2,
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
self.__layer_1_training(X, y_l1,self.__sample_wt_l1)
|
|
605
|
+
|
|
606
|
+
if isinstance(X, pd.DataFrame):
|
|
607
|
+
X_l2 = X.iloc[self.__all_ind_arr, :]
|
|
608
|
+
else:
|
|
609
|
+
X_l2 = X[self.__all_ind_arr]
|
|
610
|
+
|
|
611
|
+
y_l2 = y[self.__all_ind_arr]
|
|
612
|
+
|
|
613
|
+
# Choose only the corresponding sample weights of instances in Layer 2 (ie: instances belonging to Mixed and Pure Minority)
|
|
614
|
+
if self.__sample_wt_l2 is None:
|
|
615
|
+
modded_sample_wt_l2 = None
|
|
616
|
+
else:
|
|
617
|
+
modded_sample_wt_l2 = self.__sample_wt_l2[self.__all_ind_arr]
|
|
618
|
+
|
|
619
|
+
if not self.__apply_resample_l2:
|
|
620
|
+
self.__layer_2_training(X_l2, y_l2,modded_sample_wt_l2)
|
|
621
|
+
|
|
622
|
+
else:
|
|
623
|
+
try:
|
|
624
|
+
X_L2, y_L2 = self.__smote_obj_l2.fit_resample(X_l2, y_l2)
|
|
625
|
+
self.__layer_2_training(X_L2, y_L2,modded_sample_wt_l2)
|
|
626
|
+
|
|
627
|
+
except ValueError as e:
|
|
628
|
+
warnings.warn(f"Layer 2 SMOTE failed due to: ({e})\n Performing model fit of Layer 2 without resampling...",
|
|
629
|
+
RuntimeWarning,
|
|
630
|
+
stacklevel=2,
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
self.__layer_2_training(X_l2, y_l2,modded_sample_wt_l2)
|
|
634
|
+
|
|
635
|
+
if self.__cv_obj_l1_bool:
|
|
636
|
+
self.__final_layer1_model=self.__cv_obj_l1.best_estimator_
|
|
637
|
+
else:
|
|
638
|
+
self.__final_layer1_model=self.__model_l1
|
|
639
|
+
|
|
640
|
+
if self.__cv_obj_l2_bool:
|
|
641
|
+
self.__final_layer2_model=self.__cv_obj_l2.best_estimator_
|
|
642
|
+
else:
|
|
643
|
+
self.__final_layer2_model=self.__model_l2
|
|
644
|
+
|
|
645
|
+
# Since both the models have finished training, update the status
|
|
646
|
+
self.__dual_model = True
|
|
647
|
+
|
|
648
|
+
return self
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
@staticmethod
|
|
652
|
+
def __layer_validator(layer_name):
|
|
653
|
+
"""This function is to simply check whether the input is of a string datatype and the value is either 'L1' or 'L2'
|
|
654
|
+
|
|
655
|
+
:param layer_name: The layer for which functionalities must be accessed
|
|
656
|
+
:type layer_name: str
|
|
657
|
+
|
|
658
|
+
:return: Function will return True if the check is passed
|
|
659
|
+
:rtype: bool
|
|
660
|
+
|
|
661
|
+
:meta private:
|
|
662
|
+
"""
|
|
663
|
+
if not isinstance(layer_name,str):
|
|
664
|
+
raise ValueError("Parameter 'layer_name' is not of a string datatype!")
|
|
665
|
+
else:
|
|
666
|
+
if layer_name.upper() not in ['L1','L2']:
|
|
667
|
+
raise ValueError("Acceptable values for 'layer_name' parameter is only 'L1' or 'L2'! Please specify the proper layer name!")
|
|
668
|
+
else:
|
|
669
|
+
return True
|
|
670
|
+
|
|
671
|
+
@staticmethod
|
|
672
|
+
def __positive_class_probability(estimator, X_test, layer_name):
|
|
673
|
+
"""
|
|
674
|
+
A validation function for getting the prediction probabilities of an estimator.
|
|
675
|
+
|
|
676
|
+
:param estimator: The particular estimator of the layer for which we want probabilistic predictions.
|
|
677
|
+
:type estimator: Object
|
|
678
|
+
|
|
679
|
+
:param X_test: The test dataset over which probabilistic predictions are to be made
|
|
680
|
+
:type X_test: Pandas DataFrame or numpy.ndarray
|
|
681
|
+
|
|
682
|
+
:param layer_name: The name of the layer for which validation is to be carried out.
|
|
683
|
+
:type layer_name: string
|
|
684
|
+
|
|
685
|
+
:return: Probability of the sample for belonging to the **positive class**
|
|
686
|
+
:rtype: numpy.ndarray
|
|
687
|
+
|
|
688
|
+
:meta private:
|
|
689
|
+
"""
|
|
690
|
+
# Check whether the 'classes_' method exists and can be called for the models in both the layers
|
|
691
|
+
classes = getattr(estimator, "classes_", None)
|
|
692
|
+
if classes is None:
|
|
693
|
+
raise ValueError(f"{layer_name} estimator does not expose fitted classes_.")
|
|
694
|
+
|
|
695
|
+
# Check whether the 'predict_proba' method exists and can be called for the models in both the layers
|
|
696
|
+
predict_proba = getattr(estimator, "predict_proba", False)
|
|
697
|
+
if not callable(predict_proba):
|
|
698
|
+
raise ValueError(f"Estimator for {layer_name} must have a callable predict_proba() method!")
|
|
699
|
+
|
|
700
|
+
classes = np.asarray(classes)
|
|
701
|
+
probabilities = np.asarray(predict_proba(X_test))
|
|
702
|
+
|
|
703
|
+
if (classes.ndim != 1) or (not np.isin(classes, [0, 1]).all()):
|
|
704
|
+
raise ValueError(f"{layer_name} estimator must be fitted with binary classes 0 and 1.")
|
|
705
|
+
|
|
706
|
+
if (probabilities.ndim != 2) or (probabilities.shape != (X_test.shape[0], classes.size)):
|
|
707
|
+
raise ValueError(f"{layer_name} estimator returned an unexpected probability shape.")
|
|
708
|
+
|
|
709
|
+
# Store the indices of the array of only the positive class
|
|
710
|
+
positive_columns = np.flatnonzero(classes == 1)
|
|
711
|
+
|
|
712
|
+
# np.ndarray.size returns the count of elements throughout the entire array
|
|
713
|
+
if positive_columns.size == 1:
|
|
714
|
+
|
|
715
|
+
# positive_columns[0] is guaranteed to return the probabilities of only the positive class
|
|
716
|
+
return probabilities[:, positive_columns[0]]
|
|
717
|
+
|
|
718
|
+
else:
|
|
719
|
+
raise ValueError(f"{layer_name} estimator must have exactly one probability column for class 1.")
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def predict(self, X):
|
|
723
|
+
r"""Predict class labels for samples in X.
|
|
724
|
+
|
|
725
|
+
This class method is only valid when both the models for **Layer 1** and **Layer 2** training have a valid :py:meth:`!predict` method.
|
|
726
|
+
|
|
727
|
+
Let :math:`f_{L1}(x_i)` and :math:`f_{L2}(x_i)` denote the models trained in the layers L1 and L2, respectively. The the prediction by ICLL model is given by: :math:`f_{L1}(x_i) \cdot f_{L2}(x_i)`
|
|
728
|
+
|
|
729
|
+
Thus, a sample instance would only receive a predicted class label of 1 only when the predicted class label of that instance for both the models :math:`f_{L1}(x_i)` and :math:`f_{L2}(x_i)` is 1.
|
|
730
|
+
|
|
731
|
+
.. note::
|
|
732
|
+
|
|
733
|
+
The ICLL method :py:meth:`predict` will not work if any of the following scenarios arise by clustering:
|
|
734
|
+
|
|
735
|
+
| **Scenario 1**: No pure majority clusters are formed.
|
|
736
|
+
| **Scenario 2**: No mixed clusters are formed.
|
|
737
|
+
| **Scenario 3**: Only mixed clusters are formed.
|
|
738
|
+
|
|
739
|
+
A :py:exc:`ValueError` will be raised instead if any of the above three scenarios is encountered.
|
|
740
|
+
|
|
741
|
+
:param X: The data matrix for which we want to get the predictions.
|
|
742
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
743
|
+
|
|
744
|
+
:return: Vector containing the class labels for each sample. This would be an ndarray of shape (n_samples,)
|
|
745
|
+
:rtype: numpy.ndarray
|
|
746
|
+
|
|
747
|
+
:meta public:
|
|
748
|
+
"""
|
|
749
|
+
# Check whether the 'predict' method exists and can be called for the models in both the layers
|
|
750
|
+
if not callable(getattr(self.__final_layer1_model, "predict", False)):
|
|
751
|
+
raise ValueError(f"Estimator in Layer 1 must have a callable predict() method!")
|
|
752
|
+
|
|
753
|
+
if not callable(getattr(self.__final_layer2_model, "predict", False)):
|
|
754
|
+
raise ValueError(f"Estimator in Layer 2 must have a callable predict() method!")
|
|
755
|
+
|
|
756
|
+
# Situation where the fitted models are available on both the layers
|
|
757
|
+
if self.__dual_model:
|
|
758
|
+
yh_l1, yh_l2 = self.__final_layer1_model.predict(X), self.__final_layer2_model.predict(X)
|
|
759
|
+
|
|
760
|
+
yh_f = np.asarray([x1 * x2 for x1, x2 in zip(yh_l1, yh_l2)])
|
|
761
|
+
|
|
762
|
+
return yh_f
|
|
763
|
+
|
|
764
|
+
else:
|
|
765
|
+
raise ValueError("ICLL model has not been trained as clustering produced no pure majority clusters, no mixed clusters, or only mixed clusters.")
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def predict_proba(self, X):
|
|
769
|
+
r"""Predict probability estimates.
|
|
770
|
+
|
|
771
|
+
This class method is only valid when both the models for Layer 1 and Layer 2 training have a valid :py:meth:`!predict_proba` method.
|
|
772
|
+
|
|
773
|
+
Let :math:`f_{L1}(x_i)` and :math:`f_{L2}(x_i)` denote the models trained in the layers L1 and L2, respectively. The the prediction by ICLL model is given by: :math:`f_{L1}(x_i) \cdot f_{L2}(x_i)`
|
|
774
|
+
|
|
775
|
+
.. note::
|
|
776
|
+
|
|
777
|
+
The ICLL method :py:meth:`predict_proba` will not work if any of the following scenarios arise by clustering:
|
|
778
|
+
|
|
779
|
+
| **Scenario 1**: No pure majority clusters are formed.
|
|
780
|
+
| **Scenario 2**: No mixed clusters are formed.
|
|
781
|
+
| **Scenario 3**: Only mixed clusters are formed.
|
|
782
|
+
|
|
783
|
+
A :py:exc:`ValueError` will be raised instead if any of the above three scenarios is encountered.
|
|
784
|
+
|
|
785
|
+
|
|
|
786
|
+
| **IMPORTANT**
|
|
787
|
+
|
|
788
|
+
The ICLL model will always return the final probabilities based upon the probabilites of the positive class retured by each layer's estimator. So, to identify the probabilities returned by the positive class, the estimator corresponding to both the layers must necessarily have a :py:attr:`classes_` attribute.
|
|
789
|
+
|
|
790
|
+
If the method does not have a :py:attr:`classes_` attribute, a :py:exc:`ValueError` will be raised instead.
|
|
791
|
+
|
|
792
|
+
:param X: The data matrix for which we want to get the predictions.
|
|
793
|
+
:type X: Pandas DataFrame or numpy.ndarray
|
|
794
|
+
|
|
795
|
+
:return: Probability of the sample for belonging to the **positive class**
|
|
796
|
+
:rtype: numpy.ndarray
|
|
797
|
+
|
|
798
|
+
:meta public:
|
|
799
|
+
"""
|
|
800
|
+
|
|
801
|
+
# Situation where the fitted models are available on both the layers
|
|
802
|
+
if self.__dual_model:
|
|
803
|
+
yh_l1_p = self.__positive_class_probability(self.__final_layer1_model,X,'Layer 1')
|
|
804
|
+
yh_l2_p = self.__positive_class_probability(self.__final_layer2_model,X,'Layer 2')
|
|
805
|
+
|
|
806
|
+
yh_fp = np.asarray([x1 * x2 for x1, x2 in zip(yh_l1_p, yh_l2_p)])
|
|
807
|
+
|
|
808
|
+
return yh_fp
|
|
809
|
+
|
|
810
|
+
else:
|
|
811
|
+
raise ValueError("ICLL model has not been trained as clustering produced no pure majority clusters, no mixed clusters, or only mixed clusters.")
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def get_computed_dist_threshold(self):
|
|
815
|
+
"""Returns the log-transformed intra-cluster distance of **µ + σ**
|
|
816
|
+
|
|
817
|
+
:return: log-transformed intra-cluster distance of **µ + σ**
|
|
818
|
+
:rtype: float
|
|
819
|
+
"""
|
|
820
|
+
return self.__computed_distance
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def get_cluster_type_info(self):
|
|
824
|
+
"""Get the count of each type of cluster formed (pure majority, mixed and pure minority).
|
|
825
|
+
|
|
826
|
+
:return: A dictionary where the key is the name of the type of cluster, and its corresponding value is the count of such clusters.
|
|
827
|
+
:rtype: dict
|
|
828
|
+
"""
|
|
829
|
+
return self.__clustering_info_dict
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def get_layer_search_time(self,layer_name):
|
|
833
|
+
"""Pass 'L1' to parameter :py:attr:`layer_name` to return the time taken for hyperparameter tuning on Layer 1 when a :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object is provided.
|
|
834
|
+
Otherwise, it returns the time taken to train the **Layer 1** model.
|
|
835
|
+
|
|
836
|
+
Pass 'L2' to parameter :py:attr:`layer_name` to return the time taken for hyperparameter tuning on Layer 2 when a :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object is provided.
|
|
837
|
+
Otherwise, it returns the time taken to train the **Layer 2** model.
|
|
838
|
+
|
|
839
|
+
.. note::
|
|
840
|
+
|
|
841
|
+
The ICLL method :py:meth:`get_layer_search_time` will not work if any of the following scenarios arise by clustering:
|
|
842
|
+
|
|
843
|
+
| **Scenario 1**: No pure majority clusters are formed.
|
|
844
|
+
| **Scenario 2**: No mixed clusters are formed.
|
|
845
|
+
| **Scenario 3**: Only mixed clusters are formed.
|
|
846
|
+
|
|
847
|
+
A :py:exc:`ValueError` will be raised instead if any of the above three scenarios is encountered.
|
|
848
|
+
|
|
849
|
+
:param layer_name: The name of the layer for which functionalities are to be accessed.
|
|
850
|
+
:type layer_name: str
|
|
851
|
+
|
|
852
|
+
:return: Time measured in seconds.
|
|
853
|
+
:rtype: float
|
|
854
|
+
|
|
855
|
+
:meta public:
|
|
856
|
+
"""
|
|
857
|
+
# Validate parameter 'layer_name'
|
|
858
|
+
self.__layer_validator(layer_name)
|
|
859
|
+
|
|
860
|
+
# Convert to uppercase
|
|
861
|
+
layer_name=layer_name.upper()
|
|
862
|
+
|
|
863
|
+
# Situation where both the fitting times are available for access
|
|
864
|
+
if self.__dual_model:
|
|
865
|
+
if layer_name=='L1':
|
|
866
|
+
return self.__l1_time
|
|
867
|
+
else:
|
|
868
|
+
return self.__l2_time
|
|
869
|
+
|
|
870
|
+
else:
|
|
871
|
+
raise ValueError("ICLL model has not been trained as clustering produced no pure majority clusters, no mixed clusters, or only mixed clusters.")
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def get_fitted_cv_layer_object(self,layer_name):
|
|
875
|
+
"""Specify 'L1' or 'L2' to parameter :py:attr:`layer_name` to retrieve the fitted object for that layer. If a GridSearchCV/RandomizedSearchCV object was provided, the fitted CV object is returned.
|
|
876
|
+
|
|
877
|
+
.. note::
|
|
878
|
+
|
|
879
|
+
The ICLL method :py:meth:`get_fitted_cv_layer_object` will not work if any of the following scenarios arise by clustering:
|
|
880
|
+
|
|
881
|
+
| **Scenario 1**: No pure majority clusters are formed.
|
|
882
|
+
| **Scenario 2**: No mixed clusters are formed.
|
|
883
|
+
| **Scenario 3**: Only mixed clusters are formed.
|
|
884
|
+
|
|
885
|
+
A :py:exc:`ValueError` will be raised instead if any of the above three scenarios is encountered.
|
|
886
|
+
|
|
887
|
+
:param layer_name: The name of the layer for which functionalities are to be accessed.
|
|
888
|
+
:type layer_name: str
|
|
889
|
+
|
|
890
|
+
:return: Fitted :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object if provided at the time of object initialization.
|
|
891
|
+
:rtype: object
|
|
892
|
+
"""
|
|
893
|
+
# Validate parameter 'layer_name'
|
|
894
|
+
self.__layer_validator(layer_name)
|
|
895
|
+
|
|
896
|
+
# Convert to uppercase
|
|
897
|
+
layer_name=layer_name.upper()
|
|
898
|
+
|
|
899
|
+
# Situation where both the CV objects are available for access
|
|
900
|
+
if self.__dual_model:
|
|
901
|
+
if (layer_name=='L1'):
|
|
902
|
+
if (self.__cv_obj_l1_bool):
|
|
903
|
+
return self.__cv_obj_l1
|
|
904
|
+
else:
|
|
905
|
+
raise ValueError("Parameter 'cv_obj_l1' was empty, CV object cannot be accessed!")
|
|
906
|
+
|
|
907
|
+
else:
|
|
908
|
+
if (self.__cv_obj_l2_bool):
|
|
909
|
+
return self.__cv_obj_l2
|
|
910
|
+
else:
|
|
911
|
+
raise ValueError("Parameter 'cv_obj_l2' was empty, CV object cannot be accessed!")
|
|
912
|
+
|
|
913
|
+
else:
|
|
914
|
+
raise ValueError("ICLL model has not been trained as clustering produced no pure majority clusters, no mixed clusters, or only mixed clusters.")
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def get_fitted_model_layer_object(self,layer_name):
|
|
918
|
+
"""Specify 'L1' or 'L2' for :py:attr:`layer_name` to retrieve the fitted model from that layer. If the layer uses a :py:obj:`GridSearchCV` or :py:obj:`RandomizedSearchCV` object, the model from :py:attr:`best_estimator_` is returned. Otherwise, the fitted model stored in :py:attr:`model_l1` or :py:attr:`model_l2` is returned.
|
|
919
|
+
|
|
920
|
+
.. note::
|
|
921
|
+
|
|
922
|
+
The ICLL method :py:meth:`get_fitted_model_layer_object` will not work if any of the following scenarios arise by clustering:
|
|
923
|
+
|
|
924
|
+
| **Scenario 1**: No pure majority clusters are formed.
|
|
925
|
+
| **Scenario 2**: No mixed clusters are formed.
|
|
926
|
+
| **Scenario 3**: Only mixed clusters are formed.
|
|
927
|
+
|
|
928
|
+
A :py:exc:`ValueError` will be raised instead if any of the above three scenarios is encountered.
|
|
929
|
+
|
|
930
|
+
:param layer_name: The name of the layer for which functionalities are to be accessed.
|
|
931
|
+
:type layer_name: str
|
|
932
|
+
|
|
933
|
+
:return: Fitted model
|
|
934
|
+
:rtype: object
|
|
935
|
+
"""
|
|
936
|
+
# Validate parameter 'layer_name'
|
|
937
|
+
self.__layer_validator(layer_name)
|
|
938
|
+
|
|
939
|
+
# Convert to uppercase
|
|
940
|
+
layer_name=layer_name.upper()
|
|
941
|
+
|
|
942
|
+
# Situation where both the fitted models are available for access
|
|
943
|
+
if self.__dual_model:
|
|
944
|
+
if (layer_name=='L1'):
|
|
945
|
+
return self.__final_layer1_model
|
|
946
|
+
else:
|
|
947
|
+
return self.__final_layer2_model
|
|
948
|
+
|
|
949
|
+
else:
|
|
950
|
+
raise ValueError("ICLL model has not been trained as clustering produced no pure majority clusters, no mixed clusters, or only mixed clusters.")
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: iclltuning
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Hyperparameter Tuning on models present within Imbalanced Classification via Layered Learning (ICLL) method
|
|
5
|
+
Project-URL: Homepage, https://github.com/SVignesh2023/iclltuning
|
|
6
|
+
Project-URL: Documentation, https://iclltuning.readthedocs.io/en/latest/index.html
|
|
7
|
+
Project-URL: Issues, https://github.com/SVignesh2023/iclltuning/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/SVignesh2023/iclltuning/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Vignesh Shanmugasundaram <vigneshh2000@gmail.com>
|
|
10
|
+
Maintainer-email: Vignesh Shanmugasundaram <vigneshh2000@gmail.com>
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: Hyperparameter Tuning,Machine Learning,Model Training
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: numpy
|
|
18
|
+
Requires-Dist: pandas
|
|
19
|
+
Requires-Dist: scipy
|
|
20
|
+
Provides-Extra: cv
|
|
21
|
+
Requires-Dist: scikit-learn; extra == 'cv'
|
|
22
|
+
Provides-Extra: docs
|
|
23
|
+
Requires-Dist: sphinx; extra == 'docs'
|
|
24
|
+
Requires-Dist: sphinx-rtd-theme; extra == 'docs'
|
|
25
|
+
Provides-Extra: smote
|
|
26
|
+
Requires-Dist: imbalanced-learn; extra == 'smote'
|
|
27
|
+
Description-Content-Type: text/x-rst
|
|
28
|
+
|
|
29
|
+
iclltuning
|
|
30
|
+
==========
|
|
31
|
+
|
|
32
|
+
**iclltuning** is a library that allows hyperparameter tuning of models fed to the ICLL (Imbalanced Classification via Layered Learning) model.
|
|
33
|
+
|
|
34
|
+
Acknowledgements
|
|
35
|
+
----------------
|
|
36
|
+
|
|
37
|
+
This package is based on and extends the implementation of Imbalanced Classification via Layered Learning (ICLL) model developed by Vitor Cerqueira and collaborators.
|
|
38
|
+
|
|
39
|
+
1. Link to the research paper of ICLL: `https://arxiv.org/pdf/2205.02553v1 <https://arxiv.org/pdf/2205.02553v1>`_
|
|
40
|
+
2. Python implementation of the original ICLL algorithm: `https://github.com/vcerqueira/experiments-icll <https://github.com/vcerqueira/experiments-icll>`_
|
|
41
|
+
|
|
42
|
+
The original project is licensed under the BSD 3-Clause License.
|
|
43
|
+
A copy of the license is available in LICENSES/experiments-icll-BSD-3-Clause.txt.
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
Installation
|
|
47
|
+
------------
|
|
48
|
+
|
|
49
|
+
To install use:
|
|
50
|
+
|
|
51
|
+
.. code-block:: console
|
|
52
|
+
|
|
53
|
+
$ pip install iclltuning
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
Requirements
|
|
57
|
+
------------
|
|
58
|
+
|
|
59
|
+
* pandas
|
|
60
|
+
* numpy
|
|
61
|
+
* scipy
|
|
62
|
+
|
|
63
|
+
Read the documentation at: `https://iclltuning.readthedocs.io/en/latest/index.html <https://iclltuning.readthedocs.io/en/latest/index.html>`_
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
iclltuning/__init__.py,sha256=0iAlEp-utlDTnmibFdpbLNDxtu4rPROv1-xTCqANvxo,34
|
|
2
|
+
iclltuning/iclltuning.py,sha256=FZErC0Qm6i99g1cIvYFka6xOsoTneeTyQ79NMqAb1u4,47690
|
|
3
|
+
iclltuning-1.0.0.dist-info/METADATA,sha256=zuKkcaS_BEjSV_WVAq1108LQmgXQw5MXlUlgCf1BQvw,2303
|
|
4
|
+
iclltuning-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
iclltuning-1.0.0.dist-info/licenses/LICENSE,sha256=Sx38tTwrZKWgozAD1AM-5L_fBHNTT_iXCYKk7QvQet0,1106
|
|
6
|
+
iclltuning-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [2026] [Vignesh Shanmugasundaram]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|