Python 脚本 "Expected 2D array, got 1D array instead:" 出错?

Error in Python script "Expected 2D array, got 1D array instead:"?

我正在关注 this tutorial 进行此 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,但出现错误 "Expected 2D array, got 1D array instead:" 我认为该脚本适用于旧版本,但我不知道如何将其转换为 3.6 版本。

已经尝试过:

X.reshape(1, -1)

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

[0.58,0.76]

[[0.58,0.76]]

它应该可以工作。

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

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

当您 运行 预测数组 [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

Independent Variable和Independent Variable的X和Y矩阵分别从int64类型转为DataFrame,使其从一维数组转换为二维数组.. 即 X=pd.DataFrame(X) 和 Y=pd.dataFrame(Y) 其中 pd 是 pandas class in python。因此特征缩放反过来不会导致任何错误!

除了我想要预测的实例的数据类型是一个 panda.Series 对象之外,我遇到了同样的问题。

嗯,我只需要预测一个输入实例。我从我的一部分数据中提取了它。

df = pd.DataFrame(list(BiogasPlant.objects.all()))
test = df.iloc[-1:]       # sliced it here

在这种情况下,您需要将其转换为一维数组,然后 reshape 它。

 test2d = test.values.reshape(1,-1)

docs开始,values会将Series转换为numpy数组。

我遇到了同样的问题。您只需要将其设为一个数组,而且您必须放入双方括号以使其成为二维数组的单个元素,因为第一个括号初始化数组,第二个使其成为该数组的元素。

所以只需将最后一条语句替换为:

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

通过一项功能,我的 Dataframe 列表可以转换为 Series。我不得不将它转换回 Dataframe 列表并且它起作用了。

if type(X) is Series:
    X = X.to_frame()

我使用下面的方法。

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

我之前也遇到过同样的问题,但不知何故找到了解决方案, 你可以试试reg.predict([[3300]])

API 过去允许标量值,但现在您需要给出一个二维数组。

只需在双方括号之间插入参数:

regressor.predict([[values]])

对我有用

只需用两个方括号括起您的 numpy 对象,反之亦然。

例如:

如果最初你的x = [8,9,12,7,5]

改为x = [ [8,9,12,7,5] ]

这应该可以解决维度问题

你可以这样做:

np.array(x)[:, None]