【问题标题】:ValueError: Expected 2D array, got 1D array instead insists after converting 1D array to 2DValueError: Expected 2D array, got 1D array 相反,在将 1D 数组转换为 2D 后坚持
【发布时间】:2019-12-15 14:14:50
【问题描述】:

我查看了其他答案,但仍然无法理解为什么问题仍然存在。

Iris 数据集的经典机器学习实践。

代码:

dataset=load_iris()

X = np.array(dataset.data)
y = np.array(dataset.target)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

model = KNeighborsClassifier()
model.fit(X_train, y_train)

prediction=model.predict(X_test)

所有数组的形状:

  1. X 形状:(150, 4)
  2. y 形状:(150,)
  3. X_train: (105, 4)
  4. X_test: (45, 4)
  5. y_train: (105,)
  6. y_test (45,)
  7. 预测:(45,)

尝试打印此 model.score(y_test, prediction),但我得到了错误。 我尝试使用 .reshape(-1,1) 将 y_test 和预测转换为 2D 数组,但出现另一个错误:查询数据维度必须与训练数据维度匹配。

这不仅关乎解决方案,还关乎了解问题所在。

【问题讨论】:

    标签: python arrays numpy scikit-learn


    【解决方案1】:

    查看您使用的函数的签名和文档字符串通常很有用。 model.score 例如有

    Parameters
    ----------
    X : array-like, shape = (n_samples, n_features)
        Test samples.
    
    y : array-like, shape = (n_samples) or (n_samples, n_outputs)
        True labels for X.
    

    在文档字符串中向您显示您应该提供的确切输入类型。

    在这里你会做model.score(X_test, y_test)

    model.score 将同时进行来自X_test 的预测以及与y_test 的比较

    【讨论】:

    • 我遇到了多么意想不到的问题。我的心在千里之外。谢谢!
    猜你喜欢
    • 2021-05-05
    • 2021-11-01
    • 2018-08-25
    • 2021-07-28
    • 2018-12-23
    • 2020-10-10
    • 2020-11-22
    • 2023-03-26
    • 2018-03-20
    相关资源
    最近更新 更多