貝葉斯定理:
其中A為事件,B為種別,P(B|A)為事件A條件下屬于B種別的幾率。
樸素貝葉斯分類的正式定義以下:
1、設(shè)為1個待分類項,而每一個a為x的1個特點屬性。
2、有種別集合。
3、計算。
4、如果,則
。
那末現(xiàn)在的關(guān)鍵就是如何計算第3步中的各個條件幾率:
1、找到1個已知分類的待分類項集合,這個集合叫做訓(xùn)練樣本集。
2、統(tǒng)計得到在各種別下各個特點屬性的條件幾率估計。即 。
3、如果各個特點屬性是條件獨立的,則根據(jù)貝葉斯定理有以下推導(dǎo):
由于分母對所有種別為常數(shù),由于我們只要將份子最大化皆可。又由于各特點屬性是條件獨立的,所以有:
1、NaiveBayesModel主要的3個變量:
1)labels:種別
scala> labels
res56: Array[Double] = Array(2.0, 0.0, 1.0)
2)pi:各個label的先驗幾率
scala> pi
res57: Array[Double] = Array(⑴.1631508098056809, -0.9808292530117262, ⑴.1631508098056809)
3)theta:存儲各個特點在各個種別中的條件幾率。
scala> theta
res58: Array[Array[Double]] = Array(Array(⑵.032921526044943, ⑴.8658674413817768, -0.33647223662121295), Array(-0.2451224580329847, ⑵.179982770901713, ⑵.26002547857525), Array(⑴.9676501356917193, -0.28410425110389714, ⑵.2300144001592104))
4)lambda:平滑因子
2、NaiveBayesModel代碼
1) train
/**
* Run the algorithm with the configured parameters on an input RDD of LabeledPoint entries.
*
* @param data RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
*/
def run(data: RDD[LabeledPoint]) = {
// requireNonnegativeValues:取每個樣本數(shù)據(jù)的特點值,以向量情勢存儲,特點植必須為非負數(shù)。
val requireNonnegativeValues: Vector => Unit = (v: Vector) => {
val values = vmatch {
case SparseVector(size, indices, values) =>
values
case DenseVector(values) =>
values
}
if (!values.forall(_ >=0.0)) {
thrownew SparkException(s"Naive Bayes requires nonnegative feature values but found $v.")
}
}
// Aggregates term frequencies per label.
// TODO: Calling combineByKey and collect creates two stages, we can implement something
// TODO: similar to reduceByKeyLocally to save one stage.
// aggregated:對所有樣本數(shù)據(jù)進行聚合,以label為key,聚合同1個label的features;
// createCombiner:完成樣本從V到C的combine轉(zhuǎn)換,(v:
Vector)
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈