Word2Vec
Word2Vec is an Estimator which takes sequences of words representing documents and trains a Word2VecModel. The model maps each word to a unique fixed-size vector. The Word2VecModel transforms each document into a vector using the average of all words in the document; this vector can then be used as features for prediction, document similarity calculations, etc.
Very simple reason is machine learning algorithm can only perform on numeric values, therefore, words must be converted to numeric first, and Word2Vec is one such tool
Examples
In the following code segment, we start with a set of documents, each of which is represented as a sequence of words. For each document, we transform it into a feature vector. This feature vector could then be passed to a learning algorithm.
1
import org.apache.spark.ml.linalg.Vector
2
import org.apache.spark.sql.Row
3
import org.apache.spark.ml.feature.Word2Vec
4
​
5
// Input data: Each row is a bag of words from a sentence or document.
6
val documentDF = spark.createDataFrame(Seq(
7
"Hi I heard about Spark".split(" "),
8
"I wish Java could use case classes".split(" "),
9
"Logistic regression models are neat".split(" ")
10
).map(Tuple1.apply)).toDF("text")
11
​
12
// Learn a mapping from words to Vectors.
13
val word2Vec = new Word2Vec()
14
.setInputCol("text")
15
.setOutputCol("result")
16
.setVectorSize(3)
17
.setMinCount(0)
18
val model = word2Vec.fit(documentDF)
19
​
20
val result = model.transform(documentDF)
21
result.collect().foreach { case Row(text: Seq[_], features: Vector) =>
22
println(s"Text: [${text.mkString(", ")}] => \nVector: $features\n") }
23
24
/*
25
Text: [Hi, I, heard, about, Spark] =>
26
Vector: [-0.008142343163490296,0.02051363289356232,0.03255096450448036]
27
​
28
Text: [I, wish, Java, could, use, case, classes] =>
29
Vector: [0.043090314205203734,0.035048123182994974,0.023512658663094044]
30
​
31
Text: [Logistic, regression, models, are, neat] =>
32
Vector: [0.038572299480438235,-0.03250147425569594,-0.01552378609776497]
33
34
35
*/
36
Copied!
Last modified 1yr ago
Copy link