cerlymarco / linear-tree

A python library to build Model Trees with Linear Models at the leaves.
MIT License
338 stars 54 forks source link

How to get the coef_ and intercept_ according to the threshold #24

Closed jckkvs closed 1 year ago

jckkvs commented 1 year ago

If I apply LinearTreeRegressor when there is one explanatory variable, can I get the following range of X and regression coefficient as a table?

image

image

cerlymarco commented 1 year ago

Hi, I have difficulties understanding what you are trying to achieve... However, I can say to you that using the summary functionality you can get:

The keys are the integer map of each node. The values are dicts containing information for that node:

If you want to get coef and intercept, simply querying the interested 'models' inside the summary does the job. As an additional resource, I can suggest this post where coef_ are used

jckkvs commented 1 year ago

Thanks. Eventually I want to generate a formula below semi-automatically. y = 3 x + 0.3 if x <= 0, y = 2 x - 0.5 if 0.2 < x <= 0.5, y = 0.5*x +0.1 if 0.5 =x

When there is only one explanatory variable, these formulas are explainable and can be used as white-box AI.

To create this formula, I need a threshold, a coefficient, and an intercept, so I created the following code. However, this code can't handle complex trees, so I wanted to ask if the library you created already has such a feature.

def func(x, result):
    threshold = result.get("threshold", None)
    coef_ = result.get("coef_", None)
    intercept_ = result.get("intercept_", None)

    if threshold is None:
        coef_ = coef_
        intercept_ = intercept_
    else:
        if x <= threshold:
            coef_ = coef_[0]
            intercept_ = intercept_[0]
        elif x > threshold:
            coef_ = coef_[1]
            intercept_ = intercept_[1]
        else:
            raise ValueError    
    y = x * coef_ + intercept_    
    return y