Spark 實現 朴素貝葉斯(naiveBayes)


輸入數據說明

數據:天氣情況和每天是否踢足球的記錄表

日期 踢足球 天氣 溫度 濕度 風速
1號 否(0) 晴天(0) 熱(0) 高(0) 低(0)
2號 否(0) 晴天(0) 熱(0) 高(0) 高(1)
3號 是(1) 多雲(1) 熱(0) 高(0) 低(0)
4號 是(1) 下雨(2) 舒適(1) 高(0) 低(0)
5號 是(1) 下雨(2) 涼爽(2) 正常(1) 低(0)
6號 否(0) 下雨(2) 涼爽(2) 正常(1) 高(1)
7號 是(1) 多雲(1) 涼爽(2) 正常(1) 高(1)
8號 否(0) 晴天(0) 舒適(1) 高(0) 低(0)
9號 是(1) 晴天(0) 涼爽(2) 正常(1) 低(0)
10號 是(1) 下雨(2) 舒適(1) 正常(1) 低(0)
11號 是(1) 晴天(0) 舒適(1) 正常(1) 高(1)
12號 是(1) 多雲(1) 舒適(1) 高(0) 高(1)
13號 是(1) 多雲(1) 熱(0) 正常(1) 低(0)
14號 否(0) 下雨(2) 舒適(1) 高(0) 高(1)
15號 晴天(0) 涼爽(2) 高(0) 高(1)



數據抽象為如下,含義為是否會去踢球,天氣,溫度,濕度,風速
 

如果15號的天氣為(晴天,涼爽,濕度高,風速高,預測他是否會踢足球)

 

計算過程

假設小明15號去踢球,踢球概率為:

P(踢)=9/14

P(晴天|踢)=2/9

P(涼爽|踢)=3/9

P(濕度高|踢)=3/9

P(風速高|踢)=3/9

P(踢)由踢的天數除以總天數得到,P(晴天|踢)為踢球的同事是晴天除以踢的天數得到,其他以此類推。

P(踢|晴天,涼爽,濕度高,風速高)=

P(踢)* P(晴天|踢)* P(涼爽|踢)* P(濕度高|踢) *P(風速高|踢)=

9/14*2/9*3/9*3/9*3/9=0.00529


假設小明15號不去踢球,概率為:

P(不踢)=5/14

P(晴天|不踢)=3/5

P(涼爽|不踢)=1/5

P(濕度高|不踢)=4/5

P(風速高|不踢)=3/5

P(不踢|晴天,涼爽,濕度高,風速高)=

P(不踢)* P(晴天|不踢)* P(涼爽|不踢)* P(濕度高|不踢) *P(風速高|不踢)=

5/14*3/5*1/5*4/5*3/5=0.02057

可以看到小明不去踢足球的概率比去踢足球的概率高。


流程圖



 

 

代碼:
 
import org.apache.spark.mllib.classification.NaiveBayes
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.{SparkContext,SparkConf}

/**
* Created by yuejianjun on 16/5/18.
*/
object NaiveBayesExample1 {
def main(args: Array[String]) {
val conf = new SparkConf().setAppName("NaiveBayesExample1").setMaster("local")
val sc =new SparkContext(conf)

//讀入數據
val data = sc.textFile("/user/spark/sparkApp/src/main/resources/MLFile/tmp_naive_bayes/naive_bayes_data.txt")

val parsedData =data.map { line =>
val parts =line.split(',')
LabeledPoint(parts(0).toDouble,Vectors.dense(parts(1).split(' ').map(_.toDouble)))
}
// 把數據的60%作為訓練集,40%作為測試集.
val splits = parsedData.randomSplit(Array(0.6,0.4),seed = 11L)
val training =splits(0)
val test =splits(1)


//獲得訓練模型,第一個參數為數據,第二個參數為平滑參數,默認為1,可改
val model =NaiveBayes.train(training,lambda = 1.0)

//對模型進行准確度分析
val predictionAndLabel= test.map(p => (model.predict(p.features),p.label))
val accuracy =1.0 *predictionAndLabel.filter(x => x._1 == x._2).count() / test.count()

println("accuracy-->"+accuracy)
println("Predictionof (0.0, 2.0, 0.0, 1.0):"+model.predict(Vectors.dense(0.0,2.0,0.0,1.0)))
}
}
 

輸出結果說明:   

accuracy-->0.42857142857142855
 准確度為42%,這里是因為測試集數據量比較小的原因,所以偏差較大。


Predictionof (0.0, 2.0, 0.0, 1.0):0.0

可以從結果看到對15號的預測為不會踢球,和我們數學計算的結果一致。

 

轉:http://www.aboutyun.com/thread-12853-1-1.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM