【问题标题】:TypeError: object of type 'NoneType' has no len() when using KerasClassifierTypeError:使用 KerasClassifier 时类型为 \'NoneType\' 的对象没有 len()
【发布时间】:2022-11-17 23:07:56
【问题描述】:

我想使用 Keras 构建一个逻辑回归模型并使用 X 个时期进行训练。我想从模型中获得准确度和损失分数。 我的代码提出了TypeError: object of type 'NoneType' has no len()。但是,X_train[cv_train]y_train[cv_train] 不是NoneType

代码:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=1) 

def build_logistic_regression_model():
    model = Sequential()
    model.add(Dense(units=1,kernel_initializer='glorot_uniform', activation='sigmoid',kernel_regularizer=l2(0.)))
    
    # Performance visualization callback
    performance_viz_cbk = PerformanceVisualizationCallback(model=model,validation_data=X_val,dat_dir='c:\performance_charts')
    
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=['accuracy'])
    
    return model

lrscores = []
train_lrscores = []
for cv_train, cv_val in kfold.split(X_train, y_train):
    lr_model_logit = KerasClassifier(build_fn=build_logistic_regression_model, batch_size = 10)    
    hist = lr_model_logit.fit(X_train[cv_train], y_train[cv_train], epochs=200).history_
    losses = hist["mean_absolute_error"]
    train_lrscores.append(hist * 100)
    lr_score = hist.score(X_val, y_val)
    lrscores.append(lr_score * 100)

追溯:

/opt/conda/lib/python3.7/site-packages/scikeras/wrappers.py:302: UserWarning: ``build_fn`` will be renamed to ``model`` in a future release, at which point use of ``build_fn`` will raise an Error instead.
  "``build_fn`` will be renamed to ``model`` in a future release,"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_18384/2762271288.py in <module>
      3 for cv_train, cv_val in kfold.split(X_train, y_train):
      4     lr_model_logit = KerasClassifier(build_fn=build_logistic_regression_model, batch_size = 10)
----> 5     hist = lr_model_logit.fit(X_train[cv_train], y_train[cv_train], epochs=200).history_
      6     losses = hist["mean_absolute_error"]
      7     train_lrscores.append(hist * 100)

/opt/conda/lib/python3.7/site-packages/scikeras/wrappers.py in fit(self, X, y, sample_weight, **kwargs)
   1492             sample_weight = 1 if sample_weight is None else sample_weight
   1493             sample_weight *= compute_sample_weight(class_weight=self.class_weight, y=y)
-> 1494         super().fit(X=X, y=y, sample_weight=sample_weight, **kwargs)
   1495         return self
   1496 

/opt/conda/lib/python3.7/site-packages/scikeras/wrappers.py in fit(self, X, y, sample_weight, **kwargs)
    765             sample_weight=sample_weight,
    766             warm_start=self.warm_start,
--> 767             **kwargs,
    768         )
    769 

/opt/conda/lib/python3.7/site-packages/scikeras/wrappers.py in _fit(self, X, y, sample_weight, warm_start, epochs, initial_epoch, **kwargs)
    927         X = self.feature_encoder_.transform(X)
    928 
--> 929         self._check_model_compatibility(y)
    930 
    931         self._fit_keras_model(

/opt/conda/lib/python3.7/site-packages/scikeras/wrappers.py in _check_model_compatibility(self, y)
    549             # we recognize the attribute but do not force it to be
    550             # generated
--> 551             if self.n_outputs_expected_ != len(self.model_.outputs):
    552                 raise ValueError(
    553                     "Detected a Keras model input of size"

TypeError: object of type 'NoneType' has no len()

X_train[cv_train]

array([[ 3.49907650e-01,  1.01934833e+00,  9.22962131e-01, ...,
         4.65851423e-01,  5.85124577e-01, -2.30825406e-01],
       [-1.66145691e-01, -1.70198795e-01,  7.40812556e-01, ...,
        -1.25252966e-01,  6.11333541e-04, -1.85578709e+00],
       [-3.34532309e-01,  1.47744989e+00, -7.94889360e-01, ...,
         1.10431254e+00,  5.00866647e-01,  5.75451553e-01],
       ...,
       [-1.21341832e+00,  8.56729999e-01,  1.87070578e-01, ...,
        -8.38769062e-01, -7.08780127e-02, -6.54645722e-01],
       [ 3.45711192e-01,  8.01029131e-01,  9.37260745e-01, ...,
         6.35312010e-01, -1.77277404e-01, -1.05178867e+00],
       [ 1.65016194e+00,  1.34960903e+00,  1.17654404e+00, ...,
         3.79284887e-01,  4.38081218e-01, -3.55481467e-01]])

y_train

array([1, 3, 2, 2, 3, 2, 3, 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, 1, 3, 2, 2, 1, 1, 1, 2,
       3, 3, 2, 3, 2, 3, 1, 2, 2, 1, 2, 1, 1, 3, 3, 3, 2, 1, 1, 3, 2, 3,
       3, 2, 1, 1, 1, 2, 3, 0, 1, 2, 1, 1, 2, 0, 2, 1, 0, 2, 0, 3, 2, 3,
       2, 1, 1, 2, 3, 0, 0, 2, 2, 2, 1, 1, 1, 3, 1, 0, 1, 2, 2])

【问题讨论】:

    标签: python machine-learning keras scikit-learn logistic-regression


    【解决方案1】:

    在发布问题之前仔细查看您的代码和错误。然后,如果这没有帮助,请仔细阅读文档。

    Keras fit() documentation -> .fit() 返回什么?

    我相信你打错了字。您希望 KerasClassifier 对象具有属性 .history_。但是,这个属性显然是无,看看你的错误。

    意识到。您的错字无助于解决未来的请求,因此在这种情况下最好查看现有问题。

    Existing question

    【讨论】:

    • 感谢您的尝试。我正在从 tf.keras.wrappers.scikit_learn 迁移到 scikeras,如 adriangb.com/scikeras/stable/… 中所述。在文档中它被称为hist = clf.fit(...).history_
    猜你喜欢
    • 2021-09-13
    • 2021-03-03
    • 2015-07-30
    • 1970-01-01
    • 2018-08-14
    • 2016-06-06
    • 1970-01-01
    • 2018-06-11
    • 2021-06-14
    相关资源
    最近更新 更多