【问题标题】:'KerasClassifier' object has no attribute 'loss'“KerasClassifier”对象没有属性“损失”
【发布时间】:2020-11-30 04:47:22
【问题描述】:

我正在使用 keras 进行客户流失预测。我使用了 Sklearn 的柱式变压器。我的代码是--

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier

def keras_classifier_wrapper():
    classifier = Sequential()
    classifier.add(Dense(9, input_dim=13, activation='relu'))
    classifier.add(Dense(8, activation='relu'))
    classifier.add(Dense(1, activation='sigmoid'))
    classifier.compile(optimizer='adam', loss='binary_crossentropy',  metrics=['accuracy'])
    return clf

clf = KerasClassifier(keras_classifier_wrapper, epochs=20, batch_size=50, verbose=0)
categorical_pipe = Pipeline([
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])
numerical_pipe = Pipeline([
   ('imputer', SimpleImputer(strategy='median'))
])
 
preprocessing = ColumnTransformer(
    [('cat', categorical_pipe, cat_var1),
     ('num', numerical_pipe, num_var1)])
 
model3 = Pipeline([
    ('preprocess', preprocessing),
    ('keras_clf', clf)
])

model3.fit(X_train, y_train)

但它显示一个错误-

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-162-1f0472b386ae> in <module>()
----> 1 model3.fit(X_train, y_train)

2 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/wrappers/scikit_learn.py in fit(self, x, y, **kwargs)
    157       self.model = self.build_fn(**self.filter_sk_params(self.build_fn))
    158 
--> 159     if (losses.is_categorical_crossentropy(self.model.loss) and
    160         len(y.shape) != 2):
    161       y = to_categorical(y)

AttributeError: 'KerasClassifier' object has no attribute 'loss'

你能告诉我为什么会出现这个错误以及如何解决它。

提前致谢

【问题讨论】:

    标签: python-3.x tensorflow keras deep-learning tensorflow2.0


    【解决方案1】:

    问题出在您的 keras_classifier_wrapper 函数中

    def keras_classifier_wrapper():
        classifier = Sequential()
        classifier.add(Dense(9, input_dim=13, activation='relu'))
        classifier.add(Dense(8, activation='relu'))
        classifier.add(Dense(1, activation='sigmoid'))
        classifier.compile(optimizer='adam', loss='binary_crossentropy',  metrics=['accuracy'])
        return clf # should be return classifier
    

    您正试图返回 clf 但没有 clf 它是在之后定义的。尝试返回分类器然后它会工作

    【讨论】:

    • 显示另一个错误 ValueError: 层顺序_5 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 13,但接收到形状为 [None, 119] 的输入
    • 您的输入尺寸不一样(可能是因为一个热编码器)尝试将 input_dim 更改为 119,应该这样工作
    • 我的 X_train 是 -(460798, 13) 而 y_train 是 =460798,这只是二元分类 True & False
    • 我有 13 个特征,所以我给了 input_dim =13
    • 我明白,但您没有为网络提供这 13 个功能,您使用了一个热编码器,所以它不再是 13 个。尝试在管道外使用一个热编码器并检查您有多少功能,应该是 119。
    猜你喜欢
    • 2021-04-11
    • 2023-02-06
    • 2021-11-01
    • 1970-01-01
    • 2017-11-21
    • 2020-04-08
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多