Python脚本中的错误“预期的二维数组,而不是一维数组:”?

新手上路,请多包涵

我正在按照 本教程 进行此 ML 预测:

 import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

style.use("ggplot")
from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]

plt.scatter(x,y)
plt.show()

X = np.array([[1,2],
             [5,8],
             [1.5,1.8],
             [8,8],
             [1,0.6],
             [9,11]])

y = [0,1,0,1,0,1]
X.reshape(1, -1)

clf = svm.SVC(kernel='linear', C = 1.0)
clf.fit(X,y)

print(clf.predict([0.58,0.76]))

我正在使用 Python 3.6,但出现错误“预期 2D 数组,得到 1D 数组:”我认为该脚本适用于旧版本,但我不知道如何将其转换为 3.6 版本。

已经尝试过:

 X.reshape(1, -1)

原文由 JonTargaryen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
2 个回答

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

[0.58,0.76]

[[0.58,0.76]]

它应该工作。

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

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

原文由 Ofer Sadan 发布,翻译遵循 CC BY-SA 4.0 许可协议

当您在数组 [0.58,0.76] 上运行预测时会出现问题。通过在调用 predict() 之前重塑它来解决问题:

 import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

style.use("ggplot")
from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]

plt.scatter(x,y)
plt.show()

X = np.array([[1,2],
             [5,8],
             [1.5,1.8],
             [8,8],
             [1,0.6],
             [9,11]])

y = [0,1,0,1,0,1]

clf = svm.SVC(kernel='linear', C = 1.0)
clf.fit(X,y)

test = np.array([0.58, 0.76])
print test       # Produces: [ 0.58  0.76]
print test.shape # Produces: (2,) meaning 2 rows, 1 col

test = test.reshape(1, -1)
print test       # Produces: [[ 0.58  0.76]]
print test.shape # Produces (1, 2) meaning 1 row, 2 cols

print(clf.predict(test)) # Produces [0], as expected

原文由 stackoverflowuser2010 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题