首页 > 解决方案 > 我无法将逻辑回归拟合到模型中。如何解决这个问题?

问题描述

我在 Google Colab 中运行了这段代码:

from sklearn.metrics import confusion_matrix

# Initialize logreg model
logreg = LogisticRegression()

# Fit the model with data
logreg.fit(X_train, y_train)

# Predict model
y_pred = logreg.predict(X_test)

# Evaluate model using confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred)
print('Confusion Matrix:\n', cnf_matrix)

它给了我这个输出

<ipython-input-73-2bdb42bd97ad> in <module>()
      6 
      7 # Fit the model with data
----> 8 logreg.fit(X_train, y_train)
      9 
     10 # Predict model

1 frames
/usr/local/lib/python3.7/dist-packages/sklearn/utils/multiclass.py in check_classification_targets(y)
    167     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    168                       'multilabel-indicator', 'multilabel-sequences']:
--> 169         raise ValueError("Unknown label type: %r" % y_type)
    170 
    171 

ValueError: Unknown label type: 'unknown'

如何解决这个问题?

我的 X 变量是数字列,y 变量是标签列。我已经尝试过这段代码LogisticRegression().fit(X_train, y_train),但它也返回了错误。

标签: pythonscikit-learnlogistic-regression

解决方案


Sklearn 无法识别Boolean类型目标变量。将它们转换为数值进行训练:

y_train = y_train.astype('int')

如果您希望您的预测显示布尔值(而不是整数),您可以稍后将它们转换为Boolean

y_pred = y_pred.astype('bool')

注意:如果您决定转换您的预测,请确保您不是在预测概率,而是在预测类别(即输出是01,而不是中间值的二维矩阵;如果您确实预测概率,首先将它们转换为类别,然后进行布尔转换)。


推荐阅读