Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __init__() got an unexpected keyword argument 'categorical_features'

Spyder(python 3.7)

I am facing following errors here. I have already update all library from anaconda prompt. But can't findout the solution of the problem.

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()

X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
Traceback (most recent call last):

File "<ipython-input-4-05deb1f02719>", line 2, in <module>
onehotencoder = OneHotEncoder(categorical_features = [1])

TypeError: __init__() got an unexpected keyword argument 'categorical_features'
like image 907
Rafsan Sadman Avatar asked Dec 25 '19 07:12

Rafsan Sadman


2 Answers

So based on your code, you'd have to:

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer

# Country column
ct = ColumnTransformer([("Country", OneHotEncoder(), [1])], remainder = 'passthrough')
X = ct.fit_transform(X)

# Male/Female
labelencoder_X = LabelEncoder()
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])

Noticed how the first LabelEncoder was removed, you do not need to apply both the label encoded and the one hot encoder on the column anymore.

(I've kinda assumed your example came from the ML Udemy course, and the first column was a list of countries, while the second one a male/female binary choice)

like image 72
Antoine Jaussoin Avatar answered Oct 02 '22 20:10

Antoine Jaussoin


    from sklearn.preprocessing import OneHotEncoder
    from sklearn.compose import ColumnTransformer
    columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])],     remainder='passthrough')
    X=np.array(columnTransformer.fit_transform(X),dtype=np.str)

Since the latest build of sklearn library removed categorical_features parameter for onehotencoder class. It is advised to use ColumnTransformer class for categorical datasets. Refer the sklearn's official documentation for futher clarifications.

like image 40
Pam Cesar Avatar answered Oct 02 '22 19:10

Pam Cesar