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

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

问题描述

我正在按照本教程制作此机器学习预测:

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,但出现错误预期的二维数组,改为一维数组:"我认为该脚本适用于旧版本,但我不知道如何将其转换为 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 中显示正确的响应.当我们想要预测使用新值时,我们的程序期望相同 - 一堆的行.即使我们只想对一行(有两个值)执行此操作,该行也必须是另一个数组的一部分.

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天全站免登陆