Python脚本中的错误“预期的2D数组,改为获得1D数组:”?

问题描述 投票:41回答:7

我正在关注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并且我得到错误“预期的2D数组,而是获得了1D数组:”我认为该脚本适用于旧版本,但我不知道如何将其转换为3.6版本。

已经尝试过:

X.reshape(1, -1)
python python-3.x machine-learning predict
7个回答
84
投票

您应该为predict方法提供相同的2D数组,但要使用一个您想要处理的值(或更多)。简而言之,您只需更换即可

[0.58,0.76]

[[0.58,0.76]]

它应该工作


12
投票

在数组[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

2
投票

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

我只需要预测一个输入实例。我从一些数据中获取了它。

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

在这种情况下,您需要将其转换为1-D数组,然后将其转换为reshape

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

docsvalues将系列变成一个numpy阵列。


1
投票

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

因此,只需将最后一个语句替换为:

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

0
投票

使用一个功能,我的Dataframe列表将转换为Series。我不得不将它转换回Dataframe列表并且它有效。

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

0
投票

我使用以下方法。

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

reg.predict([[2136]])

-1
投票

独立变量和从属变量的X和Y矩阵分别来自int64类型的DataFrame,以便它从1D数组转换为2D数组..即X = pd.DataFrame(X)和Y = pd.dataFrame(Y)其中pd是python中的pandas类。因此,特征缩放又不会导致任何错误!

© www.soinside.com 2019 - 2024. All rights reserved.