One-hot encoding
One-hot encoding maps a categorical feature, represented as a label index, to a binary vector with at most a single one-value indicating the presence of a specific feature value from among the set of all feature values. This encoding allows algorithms which expect continuous features, such as Logistic Regression, to use categorical features. For string type input data, it is common to encode categorical features using StringIndexer first.
OneHotEncoderEstimator can transform multiple columns, returning an one-hot-encoded output vector column for each input column. It is common to merge these vectors into a single feature vector using VectorAssembler.
1
import org.apache.spark.ml.feature.OneHotEncoderEstimator
2
​
3
val df = spark.createDataFrame(Seq(
4
(0.0, 1.0),
5
(1.0, 0.0),
6
(2.0, 1.0),
7
(0.0, 2.0),
8
(0.0, 1.0),
9
(2.0, 0.0)
10
)).toDF("categoryIndex1", "categoryIndex2")
11
​
12
val encoder = new OneHotEncoderEstimator()
13
.setInputCols(Array("categoryIndex1", "categoryIndex2"))
14
.setOutputCols(Array("categoryVec1", "categoryVec2"))
15
val model = encoder.fit(df)
16
​
17
val encoded = model.transform(df)
18
encoded.show()
19
​
20
/*
21
+--------------+--------------+-------------+-------------+
22
|categoryIndex1|categoryIndex2| categoryVec1| categoryVec2|
23
+--------------+--------------+-------------+-------------+
24
| 0.0| 1.0|(2,[0],[1.0])|(2,[1],[1.0])|
25
| 1.0| 0.0|(2,[1],[1.0])|(2,[0],[1.0])|
26
| 2.0| 1.0| (2,[],[])|(2,[1],[1.0])|
27
| 0.0| 2.0|(2,[0],[1.0])| (2,[],[])|
28
| 0.0| 1.0|(2,[0],[1.0])|(2,[1],[1.0])|
29
| 2.0| 0.0| (2,[],[])|(2,[0],[1.0])|
30
+--------------+--------------+-------------+-------------+
31
​
32
*/
Copied!
​
Last modified 1yr ago
Copy link