使用 Python 在 Scikit Learn 中测试 DecisionTreeClassifier 时出错

Error while testing DecisionTreeClassifier in Scikit Learn with Python

我从一个csv文件中读取数据,第一行是字符串,其余都是小数。我必须将该文件中的数据从字符串转换为小数,现在正尝试 运行 对这些数据进行决策树分类。我可以很好地训练数据,但是当我调用 DecisionTreeClassifier.score() 时,我收到错误消息:"unknown is not supported"

这是我的代码:

cVal = KFold(len(file)-1, n_folds=10, shuffle=True);
for train_index, test_index in cVal:
    obfA_train, obfA_test = np.array(obfA)[train_index], np.array(obfA)[test_index]
    tTime_train, tTime_test = np.array(tTime)[train_index], np.array(tTime)[test_index]
    model = tree.DecisionTreeClassifier()
    model = model.fit(obfA_train.tolist(), tTime_train.tolist())
    print model.score(obfA_test.tolist(), tTime_test.tolist())

我之前用这些行填充了 obfA 和 tTime:

tTime.append(Decimal(file[i][11].strip('"')))
obfA[i-1][j-1] = Decimal(file[i][j].strip('"'))

所以 obfA 是一个二维数组,tTime 是一维的。之前我试过去掉上面代码中的"tolist()",但是并没有影响报错。这是它打印的错误报告:

in <module>()
---> print model.score(obfA_test.tolist(), tTime_test.tolist())

in score(self, X, y, sample_weight)
    """
    from .metrics import accuracy_score
 -->return accuracy_score(y, self.predict(X), sample_weight=sample_weight)

in accuracy_score(y_true, y_pred, normalize, sample_weight)
    # Compute accuracy for each possible representation
  ->y_type, y_true, y_pred = _check_clf_targets(y_true, y_pred)
    if y_type == 'multilabel-indicator':
        score = (y_pred != y_true).sum(axis=1) == 0

in _check_clf_targets(y_true, y_pred)
    if (y_type not in ["binary", "multiclass", "multilabel-indicator", "multilabel-sequences"]):
        -->raise ValueError("{0} is not supported".format(y_type))
    if y_type in ["binary", "multiclass"]:

ValueError: unknown is not supported

我添加了打印语句来检查输入参数的尺寸这是它打印的内容:

obfA_test.shape: (48L, 12L)
tTime_test.shape: (48L,)

我很困惑为什么错误报告显示 score() 需要 3 个参数,但文档只有 2 个。"self" 参数是什么?谁能帮我解决这个错误?

这似乎让人联想到错误discussed here。问题似乎源于您用来拟合和评分模型的数据类型。在填充输入数据数组时不要使用 Decimal,请尝试使用 float。所以我没有一个不准确的答案——你不能为 DecisionTreeClassifiers 使用 floats/continuous 值。如果您想使用浮点数,请使用 DecisionTreeRegressor。否则,请尝试使用整数或字符串(但这可能会偏离您要完成的任务)。

至于最后的自问,这是Python的句法特质。当你做 model.score(...) 时,Python 有点像对待分数 (model, ...)。恐怕我现在对它的了解不多,但没有必要回答你原来的问题。 Here's an answer that better addresses that particular question.

我意识到我遇到的问题是因为我试图使用 DecisionTreeClassifier 来预测连续值,而它们只能用于预测离散值。我将不得不改用回归模型。