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

查看:76
本文介绍了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方法提供相同的2D数组,但要提供一个或多个要处理的值.简而言之,您可以替换

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时,我们的程序会期望相同-行的.即使我们只想对一行(具有两个值)进行处理,该行也必须是另一数组的一部分.

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