Spark MLlib 機器學習演算法(一)
阿新 • • 發佈:2020-12-31
一 協同過濾演算法
協同過濾(Collaborative filtering)演算法是一種基於群體使用者或者物品的典型推薦演算法,主要有兩種:一種是通過考察具有相同愛好的使用者對相同物品的評分標準進行計算。一種是考察具有相同特質的物品從而推薦給選擇了某件物品的使用者。
協同過濾演算法關鍵是計算相似度,主要有以下幾種方法:
1、 基於歐幾里得距離計算
公式:
主要從不同目標的絕對差異性考慮
2、 基於餘弦角度計算
公式:
主要從方向趨勢上考慮
3、 交替最小二乘法(ALS)
Val ratings = data.map(_.split (‘ ’)match{
case Array(user,item,rate) => Rating(user.toInt,item.toInt,rate.toDouble)})
val model = ALS.train(ratings,rank,numIterations,0.01)
var rs = model.recommendProducts(2,1)
rs.foreach(println)
二 線性迴歸
val parsedData = sc.textFile().map{line => val parts = line.split(‘,’)
LabeledPoint(parts (0).toDouble,
Vectors.dense(parts(1).split(‘,’).map(_.toDouble)))}.cache()
val model = LinearRegressionWithSGD.train(parsedData,100,0.1)
val result = model.predict(Vectors.dense(2))
三 邏輯迴歸
1、一元邏輯迴歸
val model = LogisticRegressionWithSGD.train(parsedData,50)
val target = Vectors.dense(-1)
val result = model. predict(target)
2、支援向量機
val model = SVMWithSGD.train(parsedData,50)
3、樸素貝葉斯
val model = NaiveBayes.train(data,1.0)
val predictionAndLable = testData.map(p => (model.predict(p.features),p.label))
val accuracy = 1.0 * predictionAndLable.filter(label => label._1 == label._2).count()
(待續)