「機械学習の式の導出とコードの実装」第 15 章 - ランダム フォレスト

「機械学習の公式導出とコード実装」の学習ノート、自分の学習プロセスを記録します。詳細な内容については、著者の本を購入してください。

ランダムフォレスト

BaggingBoostingそれとは異なり、データセット自体をサンプリングして異なるサブセットを取得し、サブセットごとに基本分類器をトレーニングしてモデル統合を実行するアンサンブル学習フレームワークです

Bagging並列アンサンブル学習法です。学習フレームワークの代表的なもの随机森林で、基本分類器は2つのランダム性を組み合わせて構築され、複数の決定木からランダムフォレストが形成されます。Bagging样本特征

1 袋詰め

前の章で説明した統合学習モデルはすべて Boosting フレームワークであり、連続反復と残差フィッティングを通じて統合ツリー モデルを構築します。Bagging は並列統合学習法の最も代表的なフレームワークであり、その中心となる概念は自助采样( bootstrap sampling) にあります。データサイズが m サンプルのサンプルセットが与えられた場合、置換によりサンプルをランダムに選択してサンプルセットに入れ、m 個のサンプリングを実行すると、元のデータセットと同じサイズのサンプルセットが得られます。最後に、m 個のサンプルを含む T 個のサンプリング セットをサンプリングし、各サンプリング セットに基づいて基本分類器をトレーニングし、最後にこれらの基本分類器を組み合わせます。これがBaggingの主なアイデアです。

Bagging の最大の特徴は、Boosting がシーケンスの反復の実装であるのに対し、並列実装できることです。

ランダムフォレストの2つの基本原則

随机森林( random forest, RF) では、統合する分類器として決定木を使用し、さらに決定木の学習過程でデータセットの特徴をランダムに選択する手法を導入しているため、ランダムフォレストと呼ばれています。
簡単に言えば、ランダム フォレストのアルゴリズム プロセスは次のとおりです两个随机性

  • M 個のサンプルがあり、M 個のサンプルが置換によってランダムに選択されるとします。
  • 特徴量が N 個あるとすると、意思決定時に各ノードを分割する場合、N 個の特徴量からランダムに n 個の特徴量 (n<<N) を選択し、その n 個の特徴量からノード分割対象の特徴量を選択します。

最後に、多数の決定木を構築してランダム フォレストを形成し、各ツリーの結果を合成します (投票法は分類に使用でき、平均法は回帰に使用できます)。

3 ランダムフォレストアルゴリズムの実装

使用される決定木は CART であり、CART が実装されています

from cart import ClassificationTree
import numpy as np

class RandomForest:
    def __init__(self, n_estimators=100, min_samples_split=2, min_gain=999, max_depth=float("inf"), max_features=None):
        self.n_estimators = n_estimators
        self.min_gini_impurity = min_gain
        self.min_samples_split = min_samples_split
        self.max_depth = max_depth
        self.max_features = max_features
        self.trees = []

        # 基于决策树构造森林
        for _ in range(self.n_estimators):
            tree = ClassificationTree(
                min_samples_split=self.min_samples_split, 
                min_gini_impurity=self.min_gini_impurity, 
                max_depth=self.max_depth
            )
            self.trees.append(tree)
        
    def bootstrap_sampling(self, X, y):

        X_y = np.concatenate([X, y.reshape(-1, 1)], axis=1) # 合并数据输入和标签
        np.random.shuffle(X_y) # 打乱数据
        n_samples = X_y.shape[0] # 样本量
        sampling_subsets = [] # 初始化抽样子集列表
        # 遍历产生多个抽样子集
        for _ in range(self.n_estimators):
            # 第一个随机性,行抽样
            idx1 = np.random.choice(n_samples, n_samples, replace=True)
            bootstrap_Xy = X_y[idx1, :]
            bootstrap_X = bootstrap_Xy[:, :-1]
            bootstrap_y = bootstrap_Xy[:, -1]
            sampling_subsets.append([bootstrap_X, bootstrap_y])
        return sampling_subsets
    
    def fit(self, X, y):
        
        # 对森林中每棵树训练一个双随机抽样子集
        sub_sets = self.bootstrap_sampling(X, y)
        n_features = X.shape[1]
        # 设置max_feature
        if self.max_features == None:
            self.max_features = int(np.sqrt(n_features))
        
        # 遍历拟合每棵树
        for i in range(self.n_estimators):
            sub_X, sub_y = sub_sets[i]
            # 第二个随机性,列抽样
            idx2 = np.random.choice(n_features, self.max_features, replace=True)
            sub_X = sub_X[:, idx2]
            self.trees[i].fit(sub_X, sub_y)
            self.trees[i].feature_indices = idx2
            print(f'the {
      
      i}th tree is trained done')
    
    def predict(self, X):
        y_preds = []
        for i in range(self.n_estimators):
            idx = self.trees[i].feature_indices
            sub_X = X[:, idx]
            y_pred = self.trees[i].predict(sub_X)
            y_preds.append(y_pred)

        y_preds = np.array(y_preds).T
        res = []
        for j in y_preds:
            res.append(np.bincount(j.astype('int')).argmax())
        return res
the 0th tree is trained done
the 1th tree is trained done
the 2th tree is trained done
the 3th tree is trained done
the 4th tree is trained done
the 5th tree is trained done
the 6th tree is trained done
the 7th tree is trained done
the 8th tree is trained done
the 9th tree is trained done
0.7333333333333333

4. sklearnに基づくランダムフォレストアルゴリズムの実装

ensemble.RandomForestClassifierランダム フォレスト ベースの分類および回帰呼び出しメソッドは、それぞれ およびですensemble.RandomForestRegressor

from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(max_depth=3, random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print(acc)
0.81

Notebook_Github アドレス

おすすめ

転載: blog.csdn.net/cjw838982809/article/details/131311074