【问题标题】:TypeError: __init__() got an unexpected keyword argument 'categorical_features' Google colabTypeError: __init__() got an unexpected keyword argument 'categorical_features' Google colab
【发布时间】:2021-11-24 15:29:08
【问题描述】:

谷歌合作

这是编码分类数据的代码

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 2] = labelencoder_X_1.fit_transform(X[:, 2]) #For month
labelencoder_X_2 = LabelEncoder()
X[:, 3] = labelencoder_X_2.fit_transform(X[:, 3]) #For weekday
onehotencoder = OneHotEncoder(categorical_features = [2])#dummy variable for month
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
onehotencoder = OneHotEncoder(categorical_features = [13])#dummy variable for week
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]

我收到了这个错误,我在这里遇到了以下错误。我已经从 anaconda 提示符更新了所有库。但是找不到问题的解决办法。

TypeError                                 Traceback (most recent call last)
<ipython-input-18-faafd78b922d> in <module>()
      4 labelencoder_X_2 = LabelEncoder()
      5 X[:, 3] = labelencoder_X_2.fit_transform(X[:, 3]) #For weekday
----> 6 onehotencoder = OneHotEncoder(categorical_features = [2])#dummy variable for month
      7 X = onehotencoder.fit_transform(X).toarray()
      8 X = X[:, 1:]

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

【问题讨论】:

  • OneHotEncode构造函数中将categorical_features替换为categories,那么它应该可以工作了。
  • 使用 sklearn.compose.ColumnTransformer 并将 OneHotEncoder 作为所需参数传递给它

标签: python keras deep-learning google-colaboratory


【解决方案1】:
import pandas as pd
df=pd.read_csv('data.csv')
df

from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
df.town=le.fit_transform(df.town)
df

from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ohe=ColumnTransformer([('OHE',OneHotEncoder(),['town'])],remainder='passthrough')
x=ohe.fit_transform(df.drop('price',axis='columns'))
x=x[:,1:]#dropping the first column to avoid dummy variable trap
x

y

from sklearn.linear_model import LinearRegression
reg=LinearRegression()
reg.fit(x,y)
reg.predict([[1,0,3600]])

有关ColumnTransformer的更多详细信息。

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2017-11-01
    相关资源
    最近更新 更多