1

I am very new to using scikit library in Python, and my scikit-learn version is 0.21.2. I have used the OneHotEncoder to encode the categorical variables in my dataset.

Now I am trying to link the encoded columns back to the original variables as per the following 2 links using the codes given here and here

import pandas as pd
import numpy as np
results = []

for i in range(enc.active_features_.shape[0]):
    f = enc.active_features_[i]

    index_range = np.extract(enc.feature_indices_ <= f, enc.feature_indices_)
    s = len(index_range) - 1
    f_index = index_range[-1]
    f_label_decoded = f - f_index

    results.append({
            'label_decoded_value': f_label_decoded,
            'coefficient': clf.coef_[0][i]
        })

R = pd.DataFrame.from_records(results)
from sklearn import preprocessing
encoder = preprocessing.OneHotEncoder(categorical_features=[0,1,2])
X_train = encoder.fit_transform(data_train)
print encoder.feature_indices_

Unfortunately, it keeps throwing these errors

'OneHotEncoder' object has no attribute '_active_features_'
'OneHotEncoder' object has no attribute '_feature_indices_'

How can I solve these errors and get the codes working.

Venkatachalam
  • 16,288
  • 9
  • 49
  • 77

1 Answers1

0

I think the solutions which you were referring, actually complicates the logic more.

get_feature_names() would be just enough for it.

Example:

import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LogisticRegression

n_samples = 50
data = pd.DataFrame({'colors': np.random.choice(['red', 'blue', 'green'], n_samples),
                     'shapes': np.random.choice(['circle', 'square'], n_samples)})

y = np.random.choice(['apples', 'oranges'], n_samples)

enc = OneHotEncoder()
X = enc.fit_transform(data)
lr = LogisticRegression().fit(X, y)

pd.DataFrame({'feature_names': enc.get_feature_names(data.columns),
                      'coef': np.squeeze(lr.coef_)})

enter image description here

Venkatachalam
  • 16,288
  • 9
  • 49
  • 77