-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCtrDemo2.scala
More file actions
131 lines (107 loc) · 3.93 KB
/
Copy pathCtrDemo2.scala
File metadata and controls
131 lines (107 loc) · 3.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package io.insightedge.demo.ctr
import com.gigaspaces.spark.context.GigaSpacesConfig
import com.gigaspaces.spark.implicits._
import org.apache.spark.ml.feature.{OneHotEncoder, StringIndexer, VectorAssembler}
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS
import org.apache.spark.mllib.evaluation.BinaryClassificationMetrics
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.sql.insightedge._
import org.apache.spark.sql.{DataFrame, SQLContext}
import org.apache.spark.{SparkConf, SparkContext}
/**
* @author Oleksiy_Dyagilev
*/
object CtrDemo2 {
def main(args: Array[String]): Unit = {
if (args.length < 3) {
System.err.println("Usage: CtrDemo1 <spark master url> <grid locator> <train collection>")
System.exit(1)
}
val Array(master, gridLocator, trainCollection) = args
// Configure InsightEdge settings
val gsConfig = GigaSpacesConfig("insightedge-space", None, Some(gridLocator))
val sc = new SparkContext(new SparkConf().setAppName("CtrDemo2").setMaster(master).setGigaSpaceConfig(gsConfig))
val sqlContext = new SQLContext(sc)
// load training collection from data grid
val trainDf = sqlContext.read.grid.load(trainCollection)
trainDf.cache()
// use one-hot-encoder to convert categorical features into a vector
val encodedDf = encodeLabels(trainDf)
// assemble multiple feature vectors into a single one
val assembledDf = new VectorAssembler()
.setInputCols(categoricalColumnsVectors.toArray)
.setOutputCol("features")
.transform(encodedDf)
// convert dataframe to a label points RDD
val encodedRdd = assembledDf.map { row =>
val label = row.getAs[Double]("click")
val features = row.getAs[Vector]("features")
LabeledPoint(label, features)
}
// Split data into training (60%) and test (40%)
val Array(trainingRdd, testRdd) = encodedRdd.randomSplit(Array(0.6, 0.4), seed = 11L)
trainingRdd.cache()
// Run training algorithm to build the model
val model = new LogisticRegressionWithLBFGS()
.setNumClasses(2)
.run(trainingRdd)
// Clear the prediction threshold so the model will return probabilities
model.clearThreshold
// Compute raw scores on the test set
val predictionAndLabels = testRdd.map { case LabeledPoint(label, features) =>
val prediction = model.predict(features)
(prediction, label)
}
// Instantiate metrics object
val metrics = new BinaryClassificationMetrics(predictionAndLabels)
val auROC = metrics.areaUnderROC
println("Area under ROC = " + auROC)
}
val categoricalColumns = Seq(
// "device_id",
// "device_ip",
// "device_model",
"device_type",
"device_conn_type",
"time_day",
"time_hour",
// "C1",
// "banner_pos",
// "site_id",
// "site_domain",
// "site_category",
// "app_id",
// "app_domain",
// "app_category",
// "C14",
"C15",
"C16",
"C17",
"C18",
"C19",
"C20",
"C21"
)
val categoricalColumnsVectors = categoricalColumns.map(vectorCol)
def encodeLabel(df: DataFrame, inputColumn: String): DataFrame = {
println(s"Encoding label $inputColumn")
val indexed = new StringIndexer()
.setInputCol(inputColumn)
.setOutputCol(indexCol(inputColumn))
.fit(df)
.transform(df)
val encoder = new OneHotEncoder()
.setDropLast(false)
.setInputCol(indexCol(inputColumn))
.setOutputCol(vectorCol(inputColumn))
encoder.transform(indexed)
.drop(inputColumn)
.drop(indexCol(inputColumn))
}
def encodeLabels(df: DataFrame): DataFrame = {
categoricalColumns.foldLeft(df) { case (df, col) => encodeLabel(df, col) }
}
def vectorCol(col: String) = col + "_vector"
def indexCol(col: String) = col + "_index"
}