【问题标题】:Why am I getting the following error: y should be a 1d array, got an array of shape (423, 2) instead. (in Python)为什么我会收到以下错误:y 应该是一维数组,而是得到一个形状为 (423, 2) 的数组。 (在 Python 中)
【发布时间】:2021-08-20 19:15:47
【问题描述】:

我正在尝试使用以下代码计算逻辑回归函数的 AUC-ROC 曲线:

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)
lr_model = LogisticRegression(solver='liblinear', random_state=0).fit(x_train, y_train)
lr_test_probs = lr_model.predict_proba(x_test)
lr_auc = roc_auc_score(y_test, lr_test_probs)

当我运行它时,我收到以下错误: ValueError: y 应该是一个一维数组,得到一个形状为 (423, 2) 的数组。

我认为这是因为 y_test 的形状为 (423,2),因为它有 423 行和 2 列,第一列是索引。我试图通过使用 to_numpy() 来摆脱索引,如下所示:

y_test2=y_test.to_numpy()
y_train2=y_train.to_numpy()
x_test2=x_test.to_numpy()
x_train2=x_train.to_numpy()

但我仍然遇到同样的错误,即使当我调用 y_test2 时,它只是一个包含 0 和 1 且没有索引列的数组。 我还尝试先使用 to_numpy() 函数将 x 和 y 更改为数组,然后计算测试和训练数据,我仍然得到同样的错误。

有什么建议吗?

编辑:运行 print(y.head(5)) 给出: print(y.head(5))

【问题讨论】:

  • to_numpy 不会改变数据的形状。您需要实际提取所需的列。这回答了你的问题了吗? Extracting specific columns in numpy array
  • y 看起来像什么?为我做一个print(y.head(5)) 并将其添加到帖子中
  • @PranavHosangadi 当我尝试使用 y_test[:,1] 时出现错误:ValueError: Can only tuple-index with a MultiIndex
  • @chitown88 我将图片作为链接添加到帖子中!

标签: python train-test-split


【解决方案1】:

将 y 设置为一个系列,其中包含您的目标列名称。您也可以只选择最后一列(假设这是您想要的列)

比如:

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
y = y[['target_column_name']] # <--- insert the name of the column thats your target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)
lr_model = LogisticRegression(solver='liblinear', random_state=0).fit(x_train, y_train)
lr_test_probs = lr_model.predict_proba(x_test)
lr_auc = roc_auc_score(y_test, lr_test_probs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2021-10-06
    • 2022-01-17
    相关资源
    最近更新 更多