[技術の共有]決定木の分類

本稿では、著者:ディ殷は、承認後に発行されました。

元のリンク:https : //cloud.tencent.com/developer/article/1550440

1決定木理論

1.1決定木とは

いわゆるデシジョンツリーは、その名前が示すように、一種のツリーであり、戦略的な選択に基づいて構築された一種のツリーです。機械学習では、決定木は予測モデルであり、オブジェクト属性とオブジェクト値の間のマッピング関係を表します。ツリーの各ノードはオブジェクトを表し、各分岐パスは可能な属性値を表しますルートノードからリーフノードへのパスは、決定テストシーケンスに対応しています。デシジョンツリーの出力は1つだけです。複雑な出力が必要な場合は、独立したデシジョンツリーを作成して、さまざまな出力を処理できます。

1.2決定木学習プロセス

決定木学習の主な目的は、強力な汎化能力を持つ決定木を作成することです。基本的なプロセスは、単純で直接的な「分割統治」戦略に従います。そのプロセス実装は次のとおりです。

输入:训练集 D={(x_1,y_1),(x_2,y_2),...,(x_m,y_m)};
      属性集 A={a_1,a_2,...,a_d}
过程:函数GenerateTree(D,A)
1: 生成节点node;
2: if D中样本全属于同一类别C then
3:    将node标记为C类叶节点,并返回
4: end if
5: if A为空 OR D中样本在A上取值相同 then
6:    将node标记为叶节点,其类别标记为D中样本数量最多的类,并返回
7: end if
8: 从A中选择最优划分属性 a*;    //每个属性包含若干取值,这里假设有v个取值
9: for a* 的每个值a*_v do
10:    为node生成一个分支,令D_v表示D中在a*上取值为a*_v的样本子集;
11:    if D_v 为空 then
12:       将分支节点标记为叶节点,其类别标记为D中样本最多的类,并返回
13:    else
14:       以GenerateTree(D_v,A\{a*})为分支节点
15:    end if
16: end for

決定木の生成は再帰的なプロセスです。再帰的な戻りを引き起こす状況は3つあります。(1)現在のノードに含まれるサンプルはすべて同じカテゴリに属します。(2)現在の属性値が空であるか、すべてのサンプルがすべての属性で同じ値を取ります。(3)現在のノードに含まれているサンプルセットが空です。

(2)の場合、現在のノードをリーフノードとしてマークし、そのカテゴリを、ノードに含まれるサンプルが最も多いカテゴリに設定します。(3)の場合、現在のノードもリーフとしてマークしますノードですが、そのカテゴリは、親ノードのサンプル数が最も多いカテゴリに設定されています。2つのプロセスは本質的に異なり、前者は現在のノードの事後分布を使用し、後者は現在のノードの事前分布として親ノードの標本分布を使用します。

1.3決定木の構築

決定木を構築する上での重要なステップは、属性を分割することです(つまり、上記のプロセスの属性に対応する属性のさまざまな値を決定することa_v)。いわゆる分割属性は、特定の属性の異なる分割に従ってノードで異なる分岐を構築することであり、その目的は、各分割サブセットをできるだけ「純粋」にすることです。できるだけ「純粋」とは、分割されたサブセットに分類されるアイテムを同じカテゴリに属する​​ようにすることです。分割属性は、3つの異なる状況に分けられます。

  • 1.属性は離散値であり、二分決定木の生成を必要としません。このとき、属性の各区分がブランチとして使用されます。
  • 2.属性は離散値であり、二分決定木の生成が必要です。このとき、属性のサブセットがテストに使用され、「このサブセットに属する」と「このサブセットに属していない」の2つのブランチに分かれています。
  • 3.属性は連続的な値です。このとき、値は分割点として決定split_pointされ、>split_point合計に応じて<=split_point2つのブランチが生成されます。

1.4分割オプション

ディシジョンツリーアルゴリズムでは、最適なパーティション属性を選択する方法が最も重要なステップです。一般に、分割プロセスが進むにつれて、決定木の分岐ノードに含まれるサンプルができるだけ同じカテゴリに属する​​こと、つまりノードの「純度」が次第に高くなることを期待しています。サンプルコレクションの純度を測定するいくつかの指標があります。ではMLlib、情報エントロピーとジニインデックスが決定木の分類に使用され、分散が決定木の回帰に使用されます。

1.4.1情報エントロピー

エントロピーが最も一般的に使用される指標のサンプルセットの純度の尺度であり、現在のサンプルセットと仮定するD最初のためのkサンプルの割合は、クラスによって占めp_k、次いでDエントロピーは次のように定義されます。

Ent(D)値が小さいDほど、純度高くなります。

1.4.2ジニ係数

上記と同じ記号を使用すると、ジニ係数を使用しDデータセットの純度を測定できます

直感的に、Gini(D)それはデータセットから反射D無作為に2つのサンプルを、そのカテゴリー標識矛盾サンプリング確率。したがって、値がGini(D)小さいほど、データセットのD純度は高くなります

1.4.3分散

MLlib分散は純度の測定に使用されます。以下に示すように

1.4.4情報獲得

仮定するセグメンテーションのサイズNデータセットD二つのデータセットにD_left及びD_right、ゲイン情報は、次の形式のように表すことができます。

一般に、情報のゲインが大きいほどa属性使用して分割することで得られる純度の向上が大きくなりますしたがって、情報ゲインを使用して、決定木の属性を選択できます。これがプロセスの8番目のステップです。

1.5デシジョンツリーの利点と欠点

決定木の利点:

  • 1ディシジョンツリーは理解と説明が簡単です。
  • 2データタイプとカテゴリタイプの属性を同時に処理できる。
  • 3決定木はホワイトボックスモデルであり、観測モデルが与えられると、対応する論理式を簡単に導出できます。
  • 4比較的短い時間で大規模なデータで良い結果を出すことができます。
  • 5属性値が欠落しているサンプルの処理により適しています。

デシジョンツリーの欠点:

  • 1さまざまなカテゴリのデータ量が一貫していないデータの場合、ディシジョンツリーの種では、情報獲得の結果は、数値的特性がより高いものに偏っています。
  • 2オーバーフィットが簡単。
  • 3データセット内の属性間の相関を無視します。

2例とソースコード分析

2.1例

次の例は分類に使用されます。

import org.apache.spark.mllib.tree.DecisionTree
import org.apache.spark.mllib.tree.model.DecisionTreeModel
import org.apache.spark.mllib.util.MLUtils
// Load and parse the data file.
val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
// Split the data into training and test sets (30% held out for testing)
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(0), splits(1))
// Train a DecisionTree model.
//  Empty categoricalFeaturesInfo indicates all features are continuous.
val numClasses = 2
val categoricalFeaturesInfo = Map[Int, Int]()
val impurity = "gini"
val maxDepth = 5
val maxBins = 32
val model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo,
  impurity, maxDepth, maxBins)
// Evaluate model on test instances and compute test error
val labelAndPreds = testData.map { point =>
  val prediction = model.predict(point.features)
  (point.label, prediction)
}
val testErr = labelAndPreds.filter(r => r._1 != r._2).count().toDouble / testData.count()
println("Test Error = " + testErr)
println("Learned classification tree model:\n" + model.toDebugString)

次の例は回帰用です。

import org.apache.spark.mllib.tree.DecisionTree
import org.apache.spark.mllib.tree.model.DecisionTreeModel
import org.apache.spark.mllib.util.MLUtils
// Load and parse the data file.
val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
// Split the data into training and test sets (30% held out for testing)
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(0), splits(1))
// Train a DecisionTree model.
//  Empty categoricalFeaturesInfo indicates all features are continuous.
val categoricalFeaturesInfo = Map[Int, Int]()
val impurity = "variance"
val maxDepth = 5
val maxBins = 32
val model = DecisionTree.trainRegressor(trainingData, categoricalFeaturesInfo, impurity,
  maxDepth, maxBins)
// Evaluate model on test instances and compute test error
val labelsAndPredictions = testData.map { point =>
  val prediction = model.predict(point.features)
  (point.label, prediction)
}
val testMSE = labelsAndPredictions.map{ case (v, p) => math.pow(v - p, 2) }.mean()
println("Test Mean Squared Error = " + testMSE)
println("Learned regression tree model:\n" + model.toDebugString)

2.2ソースコード分析

ではMLlib、決定木の実現とランダムフォレストの実現が一緒になっています。ランダムフォレストの実現では、ツリーの数が1の場合、その実現はディシジョンツリーの実現です。

def run(input: RDD[LabeledPoint]): DecisionTreeModel = {
    //树个数为1
    val rf = new RandomForest(strategy, numTrees = 1, featureSubsetStrategy = "all", seed = 0)
    val rfModel = rf.run(input)
    rfModel.trees(0)
  }

ここにstrategyあるStrategy以下の情報が含まれているの例としては:

/**
 * Stores all the configuration options for tree construction
 * @param algo  Learning goal.  Supported:
 *              [[org.apache.spark.mllib.tree.configuration.Algo.Classification]],
 *              [[org.apache.spark.mllib.tree.configuration.Algo.Regression]]
 * @param impurity Criterion used for information gain calculation.
 *                 Supported for Classification: [[org.apache.spark.mllib.tree.impurity.Gini]],
 *                  [[org.apache.spark.mllib.tree.impurity.Entropy]].
 *                 Supported for Regression: [[org.apache.spark.mllib.tree.impurity.Variance]].
 * @param maxDepth Maximum depth of the tree.
 *                 E.g., depth 0 means 1 leaf node; depth 1 means 1 internal node + 2 leaf nodes.
 * @param numClasses Number of classes for classification.
 *                                    (Ignored for regression.)
 *                                    Default value is 2 (binary classification).
 * @param maxBins Maximum number of bins used for discretizing continuous features and
 *                for choosing how to split on features at each node.
 *                More bins give higher granularity.
 * @param quantileCalculationStrategy Algorithm for calculating quantiles.  Supported:
 *                             [[org.apache.spark.mllib.tree.configuration.QuantileStrategy.Sort]]
 * @param categoricalFeaturesInfo A map storing information about the categorical variables and the
 *                                number of discrete values they take. For example, an entry (n ->
 *                                k) implies the feature n is categorical with k categories 0,
 *                                1, 2, ... , k-1. It's important to note that features are
 *                                zero-indexed.
 * @param minInstancesPerNode Minimum number of instances each child must have after split.
 *                            Default value is 1. If a split cause left or right child
 *                            to have less than minInstancesPerNode,
 *                            this split will not be considered as a valid split.
 * @param minInfoGain Minimum information gain a split must get. Default value is 0.0.
 *                    If a split has less information gain than minInfoGain,
 *                    this split will not be considered as a valid split.
 * @param maxMemoryInMB Maximum memory in MB allocated to histogram aggregation. Default value is
 *                      256 MB.
 * @param subsamplingRate Fraction of the training data used for learning decision tree.
 * @param useNodeIdCache If this is true, instead of passing trees to executors, the algorithm will
 *                      maintain a separate RDD of node Id cache for each row.
 * @param checkpointInterval How often to checkpoint when the node Id cache gets updated.
 *                           E.g. 10 means that the cache will get checkpointed every 10 updates. If
 *                           the checkpoint directory is not set in
 *                           [[org.apache.spark.SparkContext]], this setting is ignored.
 */
class Strategy @Since("1.3.0") (
    @Since("1.0.0") @BeanProperty var algo: Algo,//选择的算法,有分类和回归两种选择
    @Since("1.0.0") @BeanProperty var impurity: Impurity,//纯度有熵、基尼系数、方差三种选择
    @Since("1.0.0") @BeanProperty var maxDepth: Int,//树的最大深度
    @Since("1.2.0") @BeanProperty var numClasses: Int = 2,//分类数
    @Since("1.0.0") @BeanProperty var maxBins: Int = 32,//最大子树个数
    @Since("1.0.0") @BeanProperty var quantileCalculationStrategy: QuantileStrategy = Sort,
    //保存类别变量以及相应的离散值。一个entry (n ->k) 表示特征n属于k个类别,分别是0,1,...,k-1
    @Since("1.0.0") @BeanProperty var categoricalFeaturesInfo: Map[Int, Int] = Map[Int, Int](),
    @Since("1.2.0") @BeanProperty var minInstancesPerNode: Int = 1,
    @Since("1.2.0") @BeanProperty var minInfoGain: Double = 0.0,
    @Since("1.0.0") @BeanProperty var maxMemoryInMB: Int = 256,
    @Since("1.2.0") @BeanProperty var subsamplingRate: Double = 1,
    @Since("1.2.0") @BeanProperty var useNodeIdCache: Boolean = false,
    @Since("1.2.0") @BeanProperty var checkpointInterval: Int = 10) extends Serializable

決定木の実現は、ランダムフォレスト分類のトピックで紹介されています。ここで知っておく必要があるのは、ランダムフォレスト内のツリーの数が1の場合、それは決定ツリーであり、現時点では、ツリーのトレーニングで使用される特徴は、ランダムに選択された特徴ではなく、すべての特徴です。すなわちfeatureSubsetStrategy = "all"

 

あなたの訪問を楽しみにして、プロのAI開発者コミュニティ!

Smart Titan AI Developer-Cloud + Community-Tencent Cloud cloud.tencent.com

おすすめ

転載: blog.csdn.net/qq_42933419/article/details/105250277