Sklearn:.Predict返回一个错误python



我用pip安装了sklearn,当我使用该函数时。

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:UsersRobertoAppDataLocalProgramsPythonPython36-32libsite-packagessklearntreetree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:UsersRobertoAppDataLocalProgramsPythonPython36-32libsite-
packagessklearntreetree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:UsersRobertoAppDataLocalProgramsPythonPython36-32libsite-
packagessklearnutilsvalidation.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]))

这是怎么了?

问题是您正在通过一个样本,如果您通过[[150,0]],那将是没有问题的,例如:

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

提示在错误消息中:" ...如果它包含一个示例。"问题在于,一般而言,预期的样本列表是预期的,而不仅仅是一个。传递给predict的数据应与传递给fitfeatures的格式相同,即2-D数组。尝试

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

使用此代码:

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

相关内容

最新更新