Select Language

AI Technology Community

ランダムな森のPython実現

  Pythonの2つのモジュール、pandasとscikit - learnをそれぞれ利用して、ランダムフォレストを実装します。

 


from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
 
iris = load_iris()
df = pd.Dataframe(iris.data, columns=iris.feature_names)
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75
df['species'] = pd.Factor(iris.target, iris.target_names)
df.head()
 
train, test = df[df['is_train']==True], df[df['is_train']==False]
 
features = df.columns[:4]
clf = RandomForestClassifier(n_jobs=2)
y, _ = pd.factorize(train['species'])
clf.fit(train[features], y)
 
preds = iris.target_names[clf.predict(test[features])]
pd.crosstab(test['species'], preds, rownames=['actual'], colnames=['preds'])



  分類結果:

  

  他の機械学習分類アルゴリズムとの比較:



import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.lda import LDA
from sklearn.qda import QDA
 
h = .02  # メッシュのステップサイズ
 
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree",
         "Random Forest", "AdaBoost", "Naive Bayes", "LDA", "QDA"]
classifiers = [
    KNeighborsClassifier(3),
    SVC(kernel="linear", C=0.025),
    SVC(gamma=2, C=1),
    DecisionTreeClassifier(max_depth=5),
    RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
    AdaBoostClassifier(),
    GaussianNB(),
    LDA(),
    QDA()]
 
X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
                           random_state=1, n_clusters_per_class=1)
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
linearly_separable = (X, y)
 
datasets = [make_moons(noise=0.3, random_state=0),
            make_circles(noise=0.2, factor=0.5, random_state=1),
            linearly_separable
            ]
 
figure = plt.figure(figsize=(27, 9))
i = 1
# データセットを繰り返し処理
for ds in datasets:
    # データセットを前処理し、トレーニングデータとテストデータに分割
    X, y = ds
    X = StandardScaler().fit_transform(X)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)
 
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
 
    # まずはデータセットをプロット
    cm = plt.cm.RdBu
    cm_bright = ListedColormap(['#FF0000', '#0000FF'])
    ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
    # トレーニングデータをプロット
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
    # テストデータをプロット
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())
    i += 1
 
    # 分類器を繰り返し処理
    for name, clf in zip(names, classifiers):
        ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
        clf.fit(X_train, y_train)
        score = clf.score(X_test, y_test)
 
        # 決定境界をプロットするため、メッシュ内の各点に色を割り当てる
        if hasattr(clf, "decision_function"):
            Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
        else:
            Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
 
        # 結果をカラープロットにする
        Z = Z.reshape(xx.shape)
        ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
 
        # トレーニングデータをプロット
        ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
        # テストデータをプロット
        ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
                   alpha=0.6)
 
        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xticks(())
        ax.set_yticks(())
        ax.set_title(name)
        ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
                size=15, horizontalalignment='right')
        i += 1
 
figure.subplots_adjust(left=.02, right=.98)
plt.show()


  ここでは3つのサンプルセットをランダムに生成し、分割面はそれぞれ月形、円形、線形に近似しています。決定木とランダムフォレストによるサンプル空間の分割を重点的に比較することができます:

  1)正解率からわかるように、ランダムフォレストはこの3つのテストセットすべてで単一の決定木より優れています。90%>85%、82%>80%、95% = 95%です。

  2)特徴空間から直感的にわかるように、ランダムフォレストは決定木よりも強力な分割能力(非線形フィッティング能力)を持っています。

  ランダムフォレストに関するその他のコード:

  1)Fortran版

  2)OpenCV版

  3)Matlab版

  4)R版


【注:コード部分にはそのまま英語のままの表現を残しています。Python
post
  • 6

    item of content
ランダムフォレスト(Random Forest、略してRF)は広範な応用可能性を持っており、マーケティングから医療保険まで多岐にわたり利用されています。マーケティングシミュレーションのモデリングや顧客の獲得、維持および離反の統計に使用されるだけでなく、疾患リスクや患者の感受性の予測にも用いられます。私自身、初めてこのアルゴリズムに触れたのは校外コンペティションに参加していた時でした。近年の国内外の大会、例えば2013年の百度校园电影推荐系统大赛(Baiduキャンパス映画推薦システムコンペティション)、2014年の阿里巴巴天池大数据竞赛(アリババTianchiビッグデータコンペティション)やKaggleデータサイエンスコンペティションなどでも、参加者の多くがランダムフォレストを使用しています。さらに、私の個人的な経験からも、最終選考に残ったチームの大部分がRandom ForestまたはGBDTアルゴリズムを選択していることが分かります。したがって、Random Forestはその精度において相当な優位性を持っていると言えるでしょう。