python - 我无法将逻辑回归拟合到模型中。如何解决这个问题?
问题描述
我在 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)
,但它也返回了错误。
解决方案
Sklearn 无法识别Boolean
类型目标变量。将它们转换为数值进行训练:
y_train = y_train.astype('int')
如果您希望您的预测显示布尔值(而不是整数),您可以稍后将它们转换为Boolean
:
y_pred = y_pred.astype('bool')
注意:如果您决定转换您的预测,请确保您不是在预测概率,而是在预测类别(即输出是0
和1
,而不是中间值的二维矩阵;如果您确实预测概率,首先将它们转换为类别,然后进行布尔转换)。
推荐阅读
- single-sign-on - OIDC IdP 提供商之上的代理,用于接受来自服务提供商的 SAML 请求以进行 SSO
- sql-server - 在 Management Studio 中使用 Python 自动化“生成脚本”选项以从本地 SQL Server 获取数据并将其保存在 .sql 文件中
- reactjs - onClick OverlayView react-google-maps
- visual-studio - [Broken] 在 CPU 使用率报告的 Function Name 列中表示什么?
- javascript - 将嵌套对象数组扩展为路径数组的最快方法(lodash)
- java - Netbeans warning messages for int[] and int[][] differ
- google-maps - 带有服务帐户的 Google 地理编码 API
- r - 在R中扭转情节
- c - 需要帮助在 C 中创建自己的 getch() 函数,在控制台应用程序中使用 Windows API
- python - 计算所有列中数据框的多个值