Chapter XI

Bagging (Bootstrap Aggregating)

Ensemble / ML
❦ ❦ ❦

The Source

§ I class Bagging

class Bagging:

§ II Bagging.__init__

    def __init__(self, k, n, m=None):
        self.k = k
        self.n = n
        self.m = m
        self.trees = [DecisionTree() for _ in range(n)]

§ III Bagging.fit

    def fit(self, X, y):
        idx = len(X[0])  # f: features
        Xy = concat(X, deepen(y))  # concat for convenience, sampling over 1 population
        reps = repeat_bootstrap(Xy, self.k, self.n)
        for i in range(self.n):
            X, y = split(reps[i], idx)  # idx is f + 1 - 1 = f
            self.trees[i].fit(X, ascend(y), self.m)

§ IV Bagging.predict

    def predict(self, X):
        # z : array: each element is preds of a tree
        # zz : one element of z: preds of a tree
        # tz : transposed z, each element is preds of a sample accross trees
        # tzz: one element of tz: preds of a sample accorss trees
        # y : final preds after voting: each element is the pred of a single sample
        # yy : one element of y: the pred of a single sample
        y = []
        z = []
        for i in range(self.n):
            zz = self.trees[i].predict(X)
            z.append(zz)

        # votings
        tz = t(z)  # transpose to iterate column-wise
        for tzz in tz:
            yy = most_frequent(tzz)
            y.append(yy)
        return y

§ V Demonstration

if __name__ == "__main__":
    # temperature (celsius), humidity (%)
    X = [
        [15, 40],
        [20, 35],
        [32, 85],
        [35, 90],
    ]

    # play outside?
    y = [1, 1, 0, 0]

    bagging = Bagging(k=4, n=5)

    bagging.fit(X, y)

    yy = bagging.predict([[25, 30], [35, 55], [30, 60]])
    print(yy)  # [1, 0, 0]