Scikit-learn Randomforest with warm_start results(non-broadcastable output ...)

时间:2018-03-17 08:34:34

标签: scikit-learn random-forest

我正在尝试构建一个在线随机森林分类器。在for循环中,我遇到了一个我无法找到原因的错误。

clf = RandomForestClassifier(n_estimators=1, warm_start=True)

在for循环中,我在读取新数据时增加了估算器的数量。

clf.n_estimators = (clf.n_estimators + 1)
clf = clf.fit(data_batch, label_batch)

经过循环3次后,在循环中运行代码预测如下:

predicted = clf.predict(data_batch)

我收到以下错误:

ValueError: non-broadcastable output operand with shape (500,1) doesn't match the broadcast shape (500,2)

数据处于形状(500,153)且标签为(500,)。

这是一个更完整的代码:

clf = RandomForestClassifier(n_estimators=1, warm_start=True)
clf = clf.fit(X_train, y_train)
predicted = clf.predict(X_test)

batch_size = 500

for i in xrange(batch_init_size, records, batch_size):
    from_ = (i + 1)
    to_ = (i + batch_size + 1)

    data_batch = data[from_:to_, :]
    label_batch = label[from_:to_]

    predicted = clf.predict(data_batch)

    clf.n_estimators = (clf.n_estimators + 1)
    clf = clf.fit(data_batch, label_batch)

2 个答案:

答案 0 :(得分:1)

是的,该错误是由于批次的样本类别数量不相等所致。 我通过使用将由所有类组成的批处理大小解决了这个问题。

答案 1 :(得分:0)

我找到了问题的原因: 由于数据不平衡,所以来自某些批次的所有样本都很可能来自单个类别。在这种情况下,文件forest.py无法在一个维度和一个二维矩阵上运行。以下是来自scikit-learn的forest.py中的代码:

def accumulate_prediction(predict, X, out, lock):
    prediction = predict(X, check_input=False)
    with lock:
        if len(out) == 1:
            out[0] += prediction

        else:
            for i in range(len(out)):
                out[i] += prediction[i]