-
Notifications
You must be signed in to change notification settings - Fork 89
/
LogisticRegressionUDF.scala
149 lines (132 loc) · 5.86 KB
/
LogisticRegressionUDF.scala
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.aliyun.udfs.ml
import java.lang
import org.apache.hadoop.hive.ql.exec.UDFArgumentException
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF
import org.apache.hadoop.hive.serde2.objectinspector.{ObjectInspector, StructObjectInspector}
import org.apache.hadoop.hive.serde2.objectinspector.primitive._
import org.json4s.DefaultFormats
import org.apache.spark.internal.Logging
import org.apache.spark.ml.util.ParquetFormatModelMetadataLoader
import org.apache.spark.mllib.classification.LogisticRegressionModel
import org.apache.spark.mllib.linalg._
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.sql.execution.datasources.parquet.ParquetFormatModelLoader
import org.apache.spark.sql.types._
class LogisticRegressionUDF extends GenericUDF with Logging {
var _x1: StringObjectInspector = _
var _x2: ObjectInspector = _
var isVectorType = false
override def getDisplayString(children: Array[String]): String = "Logistic_Regression"
override def initialize(arguments: Array[ObjectInspector]): ObjectInspector = {
if (arguments.length != 2) {
throw new UDFArgumentException(
s"""Logistic_Regression requires 2 arguments, got ${arguments.length}.
|Arguments should be: (modelPath, features).
|
| modelPath: LogisticRegression pre-trained model path in HDFS or OSS.
| features: data vector/string
""".stripMargin)
}
val Array(x1, x2) = arguments
if (!x1.isInstanceOf[StringObjectInspector]
|| (!x2.isInstanceOf[StructObjectInspector] && !x2.isInstanceOf[StringObjectInspector])) {
val errorMsg =
s"""Argument type error.
|(modelPath: string, features: vector)
|(${x1.isInstanceOf[StringObjectInspector]}, ${x2.isInstanceOf[StructObjectInspector]})
|or
|(modelPath: string, features: string)
|(${x1.isInstanceOf[StringObjectInspector]}, ${x2.isInstanceOf[StringObjectInspector]})
""".stripMargin
logError(errorMsg)
throw new UDFArgumentException(errorMsg)
}
_x1 = x1.asInstanceOf[StringObjectInspector]
_x2 = x2 match {
case _: StructObjectInspector =>
isVectorType = true
x2.asInstanceOf[StructObjectInspector]
case _: StringObjectInspector =>
x2.asInstanceOf[StringObjectInspector]
}
PrimitiveObjectInspectorFactory.javaDoubleObjectInspector
}
override def evaluate(arguments: Array[GenericUDF.DeferredObject]): AnyRef = {
val modelPath = _x1.getPrimitiveJavaObject(arguments(0).get())
val model = LogisticRegressionUDF.loadModel(modelPath)
val vector = if (isVectorType) {
val features = _x2.asInstanceOf[StructObjectInspector]
.getStructFieldsDataAsList(arguments(1).get())
features.get(0).asInstanceOf[Byte] match {
case 0 =>
val size = features.get(1).asInstanceOf[Int]
val indices = features.get(2).asInstanceOf[Array[Int]]
val values = features.get(3).asInstanceOf[Array[Double]]
new SparseVector(size, indices, values)
case 1 =>
val values = features.get(3).asInstanceOf[Array[Double]]
new DenseVector(values)
}
} else {
val line = _x2.asInstanceOf[StringObjectInspector].getPrimitiveJavaObject(arguments(1).get())
val record = MLUtils.parseLibSVMRecord(line)
new SparseVector(model.numFeatures, record._2, record._3)
}
new lang.Double(model.predict(vector))
}
}
object LogisticRegressionUDF {
var initialized: Boolean = false
var model: LogisticRegressionModel = _
val lock = new Object
val className = "org.apache.spark.mllib.classification.LogisticRegressionModel"
object VectorType extends VectorUDT
val requiredSchema = StructType(Array(
StructField("weights", VectorType),
StructField("intercept", DoubleType),
StructField("threshold", DoubleType)
))
def loadModel(modelPath: String): LogisticRegressionModel = {
lock.synchronized {
if (!initialized) {
val (loadedClassName, version, metadata) =
ParquetFormatModelMetadataLoader.loadModelMetaData(modelPath)
(loadedClassName, version) match {
case (clazzName, "1.0") if clazzName == className =>
implicit val formats = DefaultFormats
val numFeatures = (metadata \ "numFeatures").extract[Int]
val numClasses = (metadata \ "numClasses").extract[Int]
val (weights, intercept, threshold) =
ParquetFormatModelLoader.loadModelData(modelPath, className, requiredSchema)
model = new LogisticRegressionModel(weights, intercept, numFeatures, numClasses)
threshold match {
case Some(t) => model.setThreshold(t)
case None => model.clearThreshold()
}
initialized = true
case _ => throw new Exception(
s"ParquetFormatModelMetadataLoader.loadModel did not recognize model with " +
s"(className, format version): ($loadedClassName, $version). Supported:\n" +
s"($className, 1.0)")
}
}
model
}
}
}