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

Jon*_*yen 58 python machine-learning predict python-3.x

我正在按照本教程进行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]))
Run Code Online (Sandbox Code Playgroud)

我使用Python 3.6,我得到错误"预期的2D阵列,而不是1D阵列:"我认为该脚本适用于旧版本,但我不知道如何将其转换为3.6版本.

已经尝试过:

X.reshape(1, -1)
Run Code Online (Sandbox Code Playgroud)

Ofe*_*dan 107

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

[0.58,0.76]
Run Code Online (Sandbox Code Playgroud)

[[0.58,0.76]]
Run Code Online (Sandbox Code Playgroud)

它应该工作

  • 但为什么这样呢?我不明白这是什么问题. (24认同)
  • 为什么它必须是一个二维数组?这背后的原因是什么? (6认同)
  • 你如何为更大的数据框实现这一目标?(动态) (2认同)

sta*_*010 14

在阵列上运行预测时会发生此问题[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
Run Code Online (Sandbox Code Playgroud)


Vik*_*our 9

我使用以下方法。

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

reg.predict([[2136]])
Run Code Online (Sandbox Code Playgroud)


dev*_*saw 6

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

好吧,我只需要预测一个输入实例。我从我的数据切片中获取了它。

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

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

 test2d = test.values.reshape(1,-1)
Run Code Online (Sandbox Code Playgroud)

docsvalues将 Series 转换为一个 numpy 数组。