Python脚本“需要2D数组,而得到1D数组:”中出错?

2024-04-24 22:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在按照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]))

我使用的是Python3.6,得到的错误是“需要2D数组,而得到的是1D数组”: 我认为这个脚本是针对老版本的,但我不知道如何将其转换为3.6版本。

已尝试使用:

X.reshape(1, -1)

Tags: fromimport版本matplotlibstyleasnpplt
3条回答

我使用下面的方法。

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

reg.predict([[2136]])

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

[0.58,0.76]

[[0.58,0.76]]

它应该能起作用。

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

在这个例子中,我们在X中给计算机一组行(每个行有两个值),并在y中向它显示正确的响应。当我们想使用新的值predict时,我们的程序期望相同的行数。即使我们只想对一行(有两个值)执行此操作,该行也必须是另一个数组的一部分。

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

相关问题 更多 >