File size: 5,315 Bytes
f73646a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import numpy as np
from sklearn.feature_selection import chi2, f_classif, mutual_info_classif, mutual_info_regression
#from utils.decision import decide_pipeline



def detect_target_type(y):

    # target detection ... categorical (boolean , object , categorical numbers )

    if y.dtype == "object":
        return "categorical"


    if str(y.dtype) == "category":
        return "categorical"


    if str(y.dtype) == "bool":
        return "categorical"


    if pd.api.types.is_numeric_dtype(y):
        unique_vals = y.nunique()


        # binary or  multiclass target
        if unique_vals <= 10:
            return "categorical"

        return "numerical"

    return "categorical"


def clean_numeric_scores(series):
    # remove infinity , nan , 
    # sort descending 
    series = series.replace([np.inf, -np.inf], np.nan).dropna()
    return series.sort_values(ascending=False)



def feature_selection(df, target ,decisions ):
    results = {}

    if target not in df.columns:
        return results


    # separate columns
    
    numeric_cols = df.select_dtypes(include=["int64", "float64"]).columns.tolist()
    categorical_cols = df.select_dtypes(include=["object", "category", "bool"]).columns.tolist()


    # remove target
    if target in numeric_cols:
        numeric_cols.remove(target)


    if target in categorical_cols:
        categorical_cols.remove(target)


    # remove high cardinality categorical columns
    categorical_cols = [
        col for col in categorical_cols
        if df[col].nunique(dropna=True) <= 50
        # cardh

    ]



    y = df[target].copy()
    target_type = detect_target_type(y)

    
    # case 1 -> numerical target (regression)
    
    if target_type == "numerical":

        
        # numerical Features vs target
        
        if len(numeric_cols) > 0:
            X_num = df[numeric_cols]

            corr_scores = X_num.corrwith(y).abs()
            corr_scores = clean_numeric_scores(corr_scores)

            if len(corr_scores) > 0:
                results["numerical_correlation"] = corr_scores

            # mutual information 
            try:
                mi = mutual_info_regression(
                    X_num.fillna(X_num.median()),
                    y
                )

                mi_scores = pd.Series(
                    mi,
                    index=numeric_cols
                )


                mi_scores = clean_numeric_scores(mi_scores)


                if len(mi_scores) > 0:
                    results["numerical_mutual_info"] = mi_scores


            except:
                pass

        
        # categorical features vs target
        
        if len(categorical_cols) > 0:

            X_cat = pd.get_dummies(
                df[categorical_cols],
                drop_first=True
            )

            if X_cat.shape[1] > 0:
                try:
                    f_scores, _ = f_classif(X_cat, y)

                    anova_scores = pd.Series(
                        f_scores,
                        index=X_cat.columns
                    )

                    anova_scores = clean_numeric_scores(anova_scores)

                    if len(anova_scores) > 0:
                        results["categorical_anova"] = anova_scores

                except:
                    pass

    
    #case 2 -? categorical target (classification)
    
    else:

        y_encoded = pd.factorize(y)[0]

        
        # numeric features vs target
        
        if len(numeric_cols) > 0:

            X_num = df[numeric_cols].copy()

            # fill nulls
            for col in X_num.columns:
                X_num[col] = X_num[col].fillna(X_num[col].median())

            try:
                f_scores, _ = f_classif(X_num, y_encoded)


                anova_scores = pd.Series(
                    f_scores,
                    index=numeric_cols
                )

                anova_scores = clean_numeric_scores(anova_scores)

                if len(anova_scores) > 0:
                    results["numerical_anova"] = anova_scores

            except:
                pass

            # mutual information   ?
            try:
                mi = mutual_info_classif(X_num, y_encoded)

                mi_scores = pd.Series(
                    mi,
                    index=numeric_cols
                )


                mi_scores = clean_numeric_scores(mi_scores)

                if len(mi_scores) > 0:
                    results["numerical_mutual_info"] = mi_scores


            except:
                pass

        
        # categorical features vs target
        
        if len(categorical_cols) > 0:

            X_cat = pd.get_dummies(
                df[categorical_cols],
                drop_first=True

            )


            if X_cat.shape[1] > 0:

                try:
                    chi_scores, _ = chi2(X_cat, y_encoded)

                    chi_scores = pd.Series(
                        chi_scores,
                        index=X_cat.columns

                    )


                    chi_scores = clean_numeric_scores(chi_scores)

                    if len(chi_scores) > 0:
                        results["categorical_chi2"] = chi_scores


                except:
                    pass

    return results