Sklearn:.predict返回错误Python

时间:2017-12-06 18:18:08

标签: python scikit-learn

我用pip安装了sklearn,当我使用.predict函数时,它返回给我这个错误:

Traceback (most recent call last):
   File "C:/Users/Roberto/PycharmProjects/AI projects/New.py", line 8, in <module>
print(clf.predict([150, 0]))
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\tree\tree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\tree\tree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 150.    0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我的代码是:

from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features, labels)
print(clf.predict([150, 0]))

这有什么问题?

3 个答案:

答案 0 :(得分:2)

问题是你传递的是一个样本,如果你传递[[150,0]]就没有问题,就像这样:

print(clf.predict([[150, 0]]))

答案 1 :(得分:1)

提示位于错误消息中:&#34; ...如果它包含单个样本。&#34; 问题在于,通常预期要预测的样本列表而不是一个。传递给predict的数据格式应与传递给features的{​​{1}}格式相同,即二维数组。尝试

fit

答案 2 :(得分:0)

使用此代码:

print(clf.predict([[150, 0]]))