Python 脚本中的错误“预期的 2D 数组,而是得到 1D 数组:"? [英] Error in Python script "Expected 2D array, got 1D array instead:"?

查看:19
本文介绍了Python 脚本中的错误“预期的 2D 数组,而是得到 1D 数组:"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 本教程 来制作这个 ML预测:

I'm following this tutorial to make this ML prediction:

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 版本.

I'm using Python 3.6 and I get error "Expected 2D array, got 1D array instead:" I think the script is for older versions, but I don't know how to convert it to the 3.6 version.

已经尝试过:

X.reshape(1, -1)

推荐答案

您应该只为 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.

这篇关于Python 脚本中的错误“预期的 2D 数组,而是得到 1D 数组:"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆