【问题标题】:Is there a way to force a Random Forest Regressor to not fit an intercept?有没有办法强制随机森林回归器不适合截距?
【发布时间】:2020-07-09 12:37:27
【问题描述】:

有没有办法拟合一个 sklearn 随机森林回归器,这样一个全 0 的输入会给我一个 0 的预测?对于线性模型,我知道我可以在初始化时简单地传入 fit_intercept=False 参数,并且我想为随机森林复制它。

基于树的模型实现我想要做的事情是否有意义?如果是这样,我该如何实现?

【问题讨论】:

    标签: python machine-learning scikit-learn random-forest decision-tree


    【解决方案1】:

    简短回答:


    长答案:

    基于树的模型与线性模型非常不同;截距的概念甚至不存在于树中。

    为了了解为什么会这样,让我们​​改编documentation 中的简单示例(具有单个输入特征的决策树):

    import numpy as np
    from sklearn.tree import DecisionTreeRegressor, plot_tree
    import matplotlib.pyplot as plt
    
    # Create a random dataset
    rng = np.random.RandomState(1)
    X = np.sort(5 * rng.rand(80, 1), axis=0)
    y = np.sin(X).ravel()
    y[::5] += 3 * (0.5 - rng.rand(16))
    
    # Fit regression model
    regr = DecisionTreeRegressor(max_depth=2)
    regr.fit(X, y)
    
    # Predict
    X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
    y_pred = regr.predict(X_test)
    
    # Plot the results
    plt.figure()
    plt.scatter(X, y, s=20, edgecolor="black",
                c="darkorange", label="data")
    plt.plot(X_test, y_pred, color="cornflowerblue",
             label="max_depth=2", linewidth=2)
    plt.xlabel("data")
    plt.ylabel("target")
    plt.title("Decision Tree Regression")
    plt.legend()
    plt.show()
    

    这是输出:

    粗略地说,决策树试图在本地逼近数据,因此在它们的宇宙中不存在任何全局尝试(例如截线)。

    回归树实际作为输出返回的是因变量y平均值,这些训练样本在拟合期间最终位于相应的终端节点(叶子)中。为了看到这一点,让我们绘制上面刚刚拟合的树:

    plt.figure()
    plot_tree(regr, filled=True)
    plt.show()
    

    在这个非常简单的玩具示例中遍历树,您应该能够说服自己对X=0 的预测是0.052(左箭头是节点的True 条件)。让我们验证一下:

    regr.predict(np.array([0]).reshape(1,-1))
    # array([0.05236068])
    

    我用一个非常简单的决策树说明了上述内容,让您了解为什么这里不存在截距的概念;任何实际上基于决策树并由决策树组成的模型(如随机森林)也是如此的结论应该是直截了当的。

    【讨论】:

    • 非常感谢您提供清晰、详细的解释。非常感谢!
    猜你喜欢
    • 2019-12-06
    • 2018-12-02
    • 2023-03-14
    • 2018-05-10
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2018-06-24
    相关资源
    最近更新 更多