为sklearn的GradientBoostingClassifier生成代码

时间:2016-05-17 12:04:20

标签: python machine-learning scikit-learn boosting

我想从训练有素的梯度提升分类器(来自sklearn)生成代码(现在是Python,但最终是C)。据我了解,该模型采用初始预测器,然后从顺序训练的回归树中添加预测(按学习因子缩放)。然后,所选择的类是具有最高输出值的类。

这是我到目前为止的代码:

def recursep_gbm(left, right, threshold, features, node, depth, value, out_name, scale):
    # Functions for spacing
    tabs = lambda n: (' ' * n * 4)[:-1]
    def print_depth():
        if depth: print tabs(depth),
    def print_depth_b():
        if depth: 
            print tabs(depth), 
            if (depth-1): print tabs(depth-1),

    if (threshold[node] != -2):
        print_depth()
        print "if " + features[node] + " <= " + str(threshold[node]) + ":"
        if left[node] != -1:
            recursep_gbm(left, right, threshold, features, left[node], depth+1, value, out_name, scale)
        print_depth()
        print "else:"
        if right[node] != -1:
            recursep_gbm(left, right, threshold, features, right[node], depth+1, value, out_name, scale)
    else:
        # This is an end node, add results
        print_depth()
        print out_name + " += " + str(scale) + " * " + str(value[node][0, 0])

def print_GBM_python(gbm_model, feature_names, X_data, l_rate):
    print "PYTHON CODE"

    # Get trees
    trees = gbm_model.estimators_

    # F0
    f0_probs = np.mean(clf.predict_log_proba(X_data), axis=0)
    probs    = ", ".join([str(prob) for prob in f0_probs])
    print "# Initial probabilities (F0)"
    print "scores = np.array([%s])" % probs
    print 

    print "# Update scores for each estimator"
    for j, tree_group in enumerate(trees):
        for k, tree in enumerate(tree_group):
            left      = tree.tree_.children_left
            right     = tree.tree_.children_right
            threshold = tree.tree_.threshold
            features  = [feature_names[i] for i in tree.tree_.feature]
            value = tree.tree_.value

            recursep_gbm(left, right, threshold, features, 0, 0, value, "scores[%i]" % k, l_rate)
        print

    print "# Get class with max score"
    print "return np.argmax(scores)"

我修改了this question的树生成代码。

这是它生成的一个例子(有3个类,2个估计,1个最大深度和0.1个学习率):

# Initial probabilities (F0)
scores = np.array([-0.964890, -1.238279, -1.170222])

# Update scores for each estimator
if X1 <= 57.5:
    scores[0] += 0.1 * 1.60943587225
else:
    scores[0] += 0.1 * -0.908433703247
if X2 <= 0.000394500006223:
    scores[1] += 0.1 * -0.900203054177
else:
    scores[1] += 0.1 * 0.221484425933
if X2 <= 0.0340005010366:
    scores[2] += 0.1 * -0.848148803219
else:
    scores[2] += 0.1 * 1.98100820717

if X1 <= 57.5:
    scores[0] += 0.1 * 1.38506104792
else:
    scores[0] += 0.1 * -0.855930587354
if X1 <= 43.5:
    scores[1] += 0.1 * -0.810729087535
else:
    scores[1] += 0.1 * 0.237980820334
if X2 <= 0.027434501797:
    scores[2] += 0.1 * -0.815242297324
else:
    scores[2] += 0.1 * 1.69970863021

# Get class with max score
return np.argmax(scores)

我使用日志概率作为F0,基于this

对于一个估算器,它给出了与训练模型上的predict方法相同的预测。然而,当我添加更多估算器时,预测开始偏离。我是否应该加入步长(描述为here)?另外,我的F0是否正确?我应该采取均值吗?我应该将日志概率转换为其他东西吗?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

在Gradient Boosting分类器的引擎下是回归树的总和。

您可以通过阅读estimators_属性从受过训练的分类器中获取弱学习者决策树。从documentation开始,它实际上是DecisionTreeRegressor的ndarray。

最后,要完全重现预测功能,您还需要访问权重,如answer中所述。

或者,您可以导出决策树的GraphViz表示(而不是其伪代码)。从scikit-learn.org中找到以下可视化示例: enter image description here

作为最后的边缘注释/建议,您可能还想尝试xgboost:除了其他功能外,它还具有内置的&#34;转储模型&#34;功能(显示训练模型下的所有决策树并将其保存到文本文件中)。