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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
/*
* 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.ml.feature
import scala.collection.mutable
import org.apache.spark.annotation.AlphaComponent
import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.{IntParam, ParamMap}
import org.apache.spark.mllib.linalg._
import org.apache.spark.sql.types.DataType
/**
* :: AlphaComponent ::
* Perform feature expansion in a polynomial space. As said in wikipedia of Polynomial Expansion,
* which is available at [[http://en.wikipedia.org/wiki/Polynomial_expansion]], "In mathematics, an
* expansion of a product of sums expresses it as a sum of products by using the fact that
* multiplication distributes over addition". Take a 2-variable feature vector as an example:
* `(x, y)`, if we want to expand it with degree 2, then we get `(x, y, x * x, x * y, y * y)`.
*/
@AlphaComponent
class PolynomialExpansion extends UnaryTransformer[Vector, Vector, PolynomialExpansion] {
/**
* The polynomial degree to expand, which should be larger than 1.
* @group param
*/
val degree = new IntParam(this, "degree", "the polynomial degree to expand")
setDefault(degree -> 2)
/** @group getParam */
def getDegree: Int = getOrDefault(degree)
/** @group setParam */
def setDegree(value: Int): this.type = set(degree, value)
override protected def createTransformFunc(paramMap: ParamMap): Vector => Vector = { v =>
val d = paramMap(degree)
PolynomialExpansion.expand(v, d)
}
override protected def outputDataType: DataType = new VectorUDT()
}
/**
* The expansion is done via recursion. Given n features and degree d, the size after expansion is
* (n + d choose d) (including 1 and first-order values). For example, let f([a, b, c], 3) be the
* function that expands [a, b, c] to their monomials of degree 3. We have the following recursion:
*
* {{{
* f([a, b, c], 3) = f([a, b], 3) ++ f([a, b], 2) * c ++ f([a, b], 1) * c^2 ++ [c^3]
* }}}
*
* To handle sparsity, if c is zero, we can skip all monomials that contain it. We remember the
* current index and increment it properly for sparse input.
*/
object PolynomialExpansion {
private def choose(n: Int, k: Int): Int = {
Range(n, n - k, -1).product / Range(k, 1, -1).product
}
private def getPolySize(numFeatures: Int, degree: Int): Int = choose(numFeatures + degree, degree)
private def expandDense(
values: Array[Double],
lastIdx: Int,
degree: Int,
multiplier: Double,
polyValues: Array[Double],
curPolyIdx: Int): Int = {
if (multiplier == 0.0) {
// do nothing
} else if (degree == 0 || lastIdx < 0) {
polyValues(curPolyIdx) = multiplier
} else {
val v = values(lastIdx)
val lastIdx1 = lastIdx - 1
var alpha = multiplier
var i = 0
var curStart = curPolyIdx
while (i <= degree && alpha != 0.0) {
curStart = expandDense(values, lastIdx1, degree - i, alpha, polyValues, curStart)
i += 1
alpha *= v
}
}
curPolyIdx + getPolySize(lastIdx + 1, degree)
}
private def expandSparse(
indices: Array[Int],
values: Array[Double],
lastIdx: Int,
lastFeatureIdx: Int,
degree: Int,
multiplier: Double,
polyIndices: mutable.ArrayBuilder[Int],
polyValues: mutable.ArrayBuilder[Double],
curPolyIdx: Int): Int = {
if (multiplier == 0.0) {
// do nothing
} else if (degree == 0 || lastIdx < 0) {
polyIndices += curPolyIdx
polyValues += multiplier
} else {
// Skip all zeros at the tail.
val v = values(lastIdx)
val lastIdx1 = lastIdx - 1
val lastFeatureIdx1 = indices(lastIdx) - 1
var alpha = multiplier
var curStart = curPolyIdx
var i = 0
while (i <= degree && alpha != 0.0) {
curStart = expandSparse(indices, values, lastIdx1, lastFeatureIdx1, degree - i, alpha,
polyIndices, polyValues, curStart)
i += 1
alpha *= v
}
}
curPolyIdx + getPolySize(lastFeatureIdx + 1, degree)
}
private def expand(dv: DenseVector, degree: Int): DenseVector = {
val n = dv.size
val polySize = getPolySize(n, degree)
val polyValues = new Array[Double](polySize)
expandDense(dv.values, n - 1, degree, 1.0, polyValues, 0)
new DenseVector(polyValues)
}
private def expand(sv: SparseVector, degree: Int): SparseVector = {
val polySize = getPolySize(sv.size, degree)
val nnz = sv.values.length
val nnzPolySize = getPolySize(nnz, degree)
val polyIndices = mutable.ArrayBuilder.make[Int]
polyIndices.sizeHint(nnzPolySize)
val polyValues = mutable.ArrayBuilder.make[Double]
polyValues.sizeHint(nnzPolySize)
expandSparse(
sv.indices, sv.values, nnz - 1, sv.size - 1, degree, 1.0, polyIndices, polyValues, 0)
new SparseVector(polySize, polyIndices.result(), polyValues.result())
}
def expand(v: Vector, degree: Int): Vector = {
v match {
case dv: DenseVector => expand(dv, degree)
case sv: SparseVector => expand(sv, degree)
case _ => throw new IllegalArgumentException
}
}
}
|