且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 脚本中的错误“预期的 2D 数组,而是得到 1D 数组:"?

更新时间:2022-05-05 00:38:09

您应该只为 predict 方法提供相同的二维数组,但要处理一个值(或更多的).简而言之,你可以替换

You are just supposed to provide the predict method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace

[0.58,0.76]

[[0.58,0.76]]

它应该可以工作.

这个答案变得很流行,所以我想我会添加更多关于 ML 的解释.简短版本:我们只能对与训练数据 (X) 具有相同维度的数据使用 predict.

This answer became popular so I thought I'd add a little more explanation about ML. The short version: we can only use predict on data that is of the same dimensionality as the training data (X) was.

在有问题的示例中,我们在 X 中为计算机提供了一堆行(每个有 2 个值),并在 y 中显示正确的响应.当我们想要使用新值 predict 时,我们的程序期望相同 - bunch 行.即使我们只想对一行(具有两个值)执行此操作,该行也必须是另一个数组的一部分.

In the example in question, we give the computer a bunch of rows in X (with 2 values each) and we show it the correct responses in y. When we want to predict using new values, our program expects the same - a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.