1. 程式人生 > >梯度迭代樹(GBDT)演算法原理及Spark MLlib呼叫例項(Scala/Java/python)

梯度迭代樹(GBDT)演算法原理及Spark MLlib呼叫例項(Scala/Java/python)

梯度迭代樹

演算法簡介:

        梯度提升樹是一種決策樹的整合演算法。它通過反覆迭代訓練決策樹來最小化損失函式。決策樹類似,梯度提升樹具有可處理類別特徵、易擴充套件到多分類問題、不需特徵縮放等性質。Spark.ml通過使用現有decision tree工具來實現。

       梯度提升樹依次迭代訓練一系列的決策樹。在一次迭代中,演算法使用現有的整合來對每個訓練例項的類別進行預測,然後將預測結果與真實的標籤值進行比較。通過重新標記,來賦予預測結果不好的例項更高的權重。所以,在下次迭代中,決策樹會對先前的錯誤進行修正。

       對例項標籤進行重新標記的機制由損失函式來指定。每次迭代過程中,梯度迭代樹在訓練資料上進一步減少損失函式的值。spark.ml為分類問題提供一種損失函式(Log Loss),為迴歸問題提供兩種損失函式(平方誤差與絕對誤差)。

       Spark.ml支援二分類以及迴歸的隨機森林演算法,適用於連續特徵以及類別特徵。

*注意梯度提升樹目前不支援多分類問題。

引數:

checkpointInterval:

型別:整數型。

含義:設定檢查點間隔(>=1),或不設定檢查點(-1)。

featuresCol:

型別:字串型。

含義:特徵列名。

impurity:

型別:字串型。

含義:計算資訊增益的準則(不區分大小寫)。

labelCol:

型別:字串型。

含義:標籤列名。

lossType:

型別:字串型。

含義:損失函式型別。

maxBins:

型別:整數型。

含義:連續特徵離散化的最大數量,以及選擇每個節點分裂特徵的方式。

maxDepth:

型別:整數型。

含義:樹的最大深度(>=0)。

maxIter:

型別:整數型。

含義:迭代次數(>=0)。

minInfoGain:

型別:雙精度型。

含義:分裂節點時所需最小資訊增益。

minInstancesPerNode:

型別:整數型。

含義:分裂後自節點最少包含的例項數量。

predictionCol:

型別:字串型。

含義:預測結果列名。

rawPredictionCol:

型別:字串型。

含義:原始預測。

seed:

型別:長整型。

含義:隨機種子。

subsamplingRate:

型別:雙精度型。

含義:學習一棵決策樹使用的訓練資料比例,範圍[0,1]。

stepSize:

型別:雙精度型。

含義:每次迭代優化步長。

示例:

       下面的例子匯入LibSVM格式資料,並將之劃分為訓練資料和測試資料。使用第一部分資料進行訓練,剩下資料來測試。訓練之前我們使用了兩種資料預處理方法來對特徵進行轉換,並且添加了元資料到DataFrame。

Scala:

import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.classification.{GBTClassificationModel, GBTClassifier}
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}

// Load and parse the data file, converting it to a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Index labels, adding metadata to the label column.
// Fit on whole dataset to include all labels in index.
val labelIndexer = new StringIndexer()
  .setInputCol("label")
  .setOutputCol("indexedLabel")
  .fit(data)
// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a GBT model.
val gbt = new GBTClassifier()
  .setLabelCol("indexedLabel")
  .setFeaturesCol("indexedFeatures")
  .setMaxIter(10)

// Convert indexed labels back to original labels.
val labelConverter = new IndexToString()
  .setInputCol("prediction")
  .setOutputCol("predictedLabel")
  .setLabels(labelIndexer.labels)

// Chain indexers and GBT in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(labelIndexer, featureIndexer, gbt, labelConverter))

// Train model. This also runs the indexers.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("predictedLabel", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("indexedLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("Test Error = " + (1.0 - accuracy))

val gbtModel = model.stages(2).asInstanceOf[GBTClassificationModel]
println("Learned classification GBT model:\n" + gbtModel.toDebugString)

Java:
import org.apache.spark.ml.Pipeline;
import org.apache.spark.ml.PipelineModel;
import org.apache.spark.ml.PipelineStage;
import org.apache.spark.ml.classification.GBTClassificationModel;
import org.apache.spark.ml.classification.GBTClassifier;
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
import org.apache.spark.ml.feature.*;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

// Load and parse the data file, converting it to a DataFrame.
Dataset<Row> data = spark
  .read()
  .format("libsvm")
  .load("data/mllib/sample_libsvm_data.txt");

// Index labels, adding metadata to the label column.
// Fit on whole dataset to include all labels in index.
StringIndexerModel labelIndexer = new StringIndexer()
  .setInputCol("label")
  .setOutputCol("indexedLabel")
  .fit(data);
// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
VectorIndexerModel featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data);

// Split the data into training and test sets (30% held out for testing)
Dataset<Row>[] splits = data.randomSplit(new double[] {0.7, 0.3});
Dataset<Row> trainingData = splits[0];
Dataset<Row> testData = splits[1];

// Train a GBT model.
GBTClassifier gbt = new GBTClassifier()
  .setLabelCol("indexedLabel")
  .setFeaturesCol("indexedFeatures")
  .setMaxIter(10);

// Convert indexed labels back to original labels.
IndexToString labelConverter = new IndexToString()
  .setInputCol("prediction")
  .setOutputCol("predictedLabel")
  .setLabels(labelIndexer.labels());

// Chain indexers and GBT in a Pipeline.
Pipeline pipeline = new Pipeline()
  .setStages(new PipelineStage[] {labelIndexer, featureIndexer, gbt, labelConverter});

// Train model. This also runs the indexers.
PipelineModel model = pipeline.fit(trainingData);

// Make predictions.
Dataset<Row> predictions = model.transform(testData);

// Select example rows to display.
predictions.select("predictedLabel", "label", "features").show(5);

// Select (prediction, true label) and compute test error.
MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("indexedLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy");
double accuracy = evaluator.evaluate(predictions);
System.out.println("Test Error = " + (1.0 - accuracy));

GBTClassificationModel gbtModel = (GBTClassificationModel)(model.stages()[2]);
System.out.println("Learned classification GBT model:\n" + gbtModel.toDebugString());

Python:
from pyspark.ml import Pipeline
from pyspark.ml.classification import GBTClassifier
from pyspark.ml.feature import StringIndexer, VectorIndexer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator

# Load and parse the data file, converting it to a DataFrame.
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

# Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
labelIndexer = StringIndexer(inputCol="label", outputCol="indexedLabel").fit(data)
# Automatically identify categorical features, and index them.
# Set maxCategories so features with > 4 distinct values are treated as continuous.
featureIndexer =\
    VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4).fit(data)

# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])

# Train a GBT model.
gbt = GBTClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures", maxIter=10)

# Chain indexers and GBT in a Pipeline
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, gbt])

# Train model.  This also runs the indexers.
model = pipeline.fit(trainingData)

# Make predictions.
predictions = model.transform(testData)

# Select example rows to display.
predictions.select("prediction", "indexedLabel", "features").show(5)

# Select (prediction, true label) and compute test error
evaluator = MulticlassClassificationEvaluator(
    labelCol="indexedLabel", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictions)
print("Test Error = %g" % (1.0 - accuracy))

gbtModel = model.stages[2]
print(gbtModel)  # summary only


相關推薦

梯度GBDT演算法原理Spark MLlib呼叫例項Scala/Java/python

梯度迭代樹 演算法簡介:         梯度提升樹是一種決策樹的整合演算法。它通過反覆迭代訓練決策樹來最小化損失函式。決策樹類似,梯度提升樹具有可處理類別特徵、易擴充套件到多分類問題、不需特徵縮放等性質。Spark.ml通過使用現有decision tree工具來實現。

多層感知機MLP演算法原理Spark MLlib呼叫例項Scala/Java/Python

多層感知機 演算法簡介:         多層感知機是基於反向人工神經網路(feedforwardartificial neural network)。多層感知機含有多層節點,每層節點與網路的下一層節點完全連線。輸入層的節點代表輸入資料,其他層的節點通過將輸入資料與層上節點

MLlib--多層感知機MLP演算法原理Spark MLlib呼叫例項Scala/Java/Python

來源:http://blog.csdn.net/liulingyuan6/article/details/53432429 多層感知機 演算法簡介:         多層感知機是基於反向人工神經網路(feedforwardartificial neural net

隨機森林迴歸Random Forest演算法原理Spark MLlib呼叫例項Scala/Java/python

隨機森林迴歸 演算法介紹:        隨機森林是決策樹的整合演算法。隨機森林包含多個決策樹來降低過擬合的風險。隨機森林同樣具有易解釋性、可處理類別特徵、易擴充套件到多分類問題、不需特徵縮放等性質。 隨機森林分別訓練一系列的決策樹,所以訓練過程是並行的。因演算法中加入隨機

二分K均值演算法原理Spark MLlib呼叫例項(Scala/Java/Python)

二分K均值演算法 演算法介紹: 二分K均值演算法是一種層次聚類演算法,使用自頂向下的逼近:所有的觀察值開始是一個簇,遞迴地向下一個層級分裂。分裂依據為選擇能最大程度降低聚類代價函式(也就是誤差平方和)的簇劃分為兩個簇。以此進行下去,直到簇的數目等於使用者給定的數目k為止。二

二十種特徵變換方法Spark MLlib呼叫例項Scala/Java/python

Tokenizer(分詞器) 演算法介紹:         Tokenization將文字劃分為獨立個體(通常為單詞)。下面的例子展示瞭如何把句子劃分為單詞。         RegexTokenizer基於正則表示式提供更多的劃分選項。預設情況下,引數“pattern”為

三種特徵選擇方法Spark MLlib呼叫例項Scala/Java/python

VectorSlicer 演算法介紹:         VectorSlicer是一個轉換器輸入特徵向量,輸出原始特徵向量子集。VectorSlicer接收帶有特定索引的向量列,通過對這些索引的值進行篩選得到新的向量集。可接受如下兩種索引 1.整數索引,setIndice

二十種特徵變換方法Spark MLlib呼叫例項Scala/Java/python

VectorIndexer 演算法介紹:         VectorIndexer解決資料集中的類別特徵Vector。它可以自動識別哪些特徵是類別型的,並且將原始值轉換為類別指標。它的處理流程如下: 1.獲得一個向量型別的輸入以及maxCategories引數。 2.基於

演算法學習】AVL平衡二叉搜尋原理各項操作程式設計實現C++

AVLTree即(Adelson-Velskii-Landis Tree),是加了額外條件的二叉搜尋樹。其平衡條件的建立是為了確保整棵樹的深度為O(nLogn)。平衡條件是任何節點的左右子樹的高度相差不超過1. 在下面的程式碼中,程式設計實現了AVL樹的建立、查詢、插入、

寫程式學ML:決策演算法原理實現

[題外話]近期申請了一個微信公眾號:平凡程式人生。有興趣的朋友可以關注,那裡將會涉及更多更新機器學習、OpenCL+OpenCV以及影象處理方面的文章。 2.3   決策樹的測試 書中使用隱形眼鏡資料集對決策樹進行了測試。 建立測試檔案contactLenses4Deci

Apache Spark MLlib學習筆記MLlib決策演算法原始碼解析 2

上篇說道建立分類決策樹模型呼叫了trainClassifier方法,這章分析trainClassifier方法相關內容 按照以下路徑開啟原始碼檔案: /home/yangqiao/codes/spark/mllib/src/main/scala/org/ap

深度學習之神經網路CNN/RNN/GAN演算法原理+實戰目前最新

第1章 課程介紹 深度學習的導學課程,主要介紹了深度學習的應用範疇、人才需求情況和主要演算法。對課程章節、課程安排、適用人群、前提條件以及學習完成後達到的程度進行了介紹,讓同學們對本課程有基本的認識。 1-1 課程導學 第2章 神經網路入門 本次實戰課程的入門課程。對機器學習和深度學習做了引入

【機器學習】Apriori演算法——原理程式碼實現Python

Apriopri演算法 Apriori演算法在資料探勘中應用較為廣泛,常用來挖掘屬性與結果之間的相關程度。對於這種尋找資料內部關聯關係的做法,我們稱之為:關聯分析或者關聯規則學習。而Apriori演算法就是其中非常著名的演算法之一。關聯分析,主要是通過演算法在大規模資料集中尋找頻繁項集和關聯規則。

deformable convolution可變形卷積演算法解析程式碼分析

可變形卷積是指卷積核在每一個元素上額外增加了一個引數方向引數,這樣卷積核就能在訓練過程中擴充套件到很大的範圍。 可變形卷積的論文為:Deformable Convolutional Networks【1】 而之前google一篇論文對這篇論文有指導意義:Spatial

《Kalman濾波原理應用》學習筆記——Kalman濾波演算法在溫度測量中的應用

Kalman濾波器 考慮用如下狀態空間模型描述的動態系統(1.1)X(k+1)=ΦX(k)+ΓW(k)X(k+1)=\Phi X(k)+\Gamma W(k) \tag{1.1}X(k+1)=ΦX(k)+ΓW(k)(1.1)(1.2)Y(k)=HX(k)+V(

簡單選擇排序演算法原理java實現超詳細

選擇排序是一種非常簡單的排序演算法,就是在序列中依次選擇最大(或者最小)的數,並將其放到待排序的數列的起始位置。 簡單選擇排序的原理 簡單選擇排序的原理非常簡單,即在待排序的數列中尋找最大(或者最小)的一個數,與第 1 個元素進行交換,接著在剩餘的待排序的數列中繼續找最大(最小)的一個數,與第 2 個元素交

【原創】大數據基礎之Spark4RDD原理碼解析

sso 數據 queue running upd parallel input gettime side 一 簡介 spark核心是RDD,官方文檔地址:https://spark.apache.org/docs/latest/rdd-programming-guide.h

氣泡排序演算法原理實現超詳細

氣泡排序(Bubble Sort)是排序演算法裡面比較簡單的一個排序。它重複地走訪要排序的數列,一次比較兩個資料元素,如果順序不對則進行交換,並一直重複這樣的走訪操作,直到沒有要交換的資料元素為止。 氣泡排序的原理 為了更深入地理解氣泡排序的操作步驟,我們現在看一下氣泡排序的原理。 首先我們肯定有一個數組

快速排序演算法原理實現單軸快速排序、三向切分快速排序、雙軸快速排序

歡迎探討,如有錯誤敬請指正 1. 單軸快速排序的基本原理 快速排序的基本思想就是從一個數組中任意挑選一個元素(通常來說會選擇最左邊的元素)作為中軸元素,將剩下的元素以中軸元素作為比較的標準,將小於等於中軸元素的放到中軸元素的左邊,將大於中軸元素的放到中軸元素的右邊,然後以當前中軸元素的位置為界,將左半部分子

偏最小二乘迴歸PLSR演算法原理

1、問題的提出   在跨媒體檢索領域中,CCA(Canonical correlation analysis,典型關聯分析)是應用最為廣泛的演算法之一。CCA可以把兩種媒體的原始特徵空間對映對映到相關的兩個特徵子空間中,從而實現兩個屬於不同媒體的樣本之間的相似