-
Notifications
You must be signed in to change notification settings - Fork 28.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Spark-8703] [ML] Add CountVectorizer as a ml transformer to convert document to words count vector #7084
Closed
Closed
[Spark-8703] [ML] Add CountVectorizer as a ml transformer to convert document to words count vector #7084
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7c61fb3
add countVectorizer
hhbyyh 809fb59
minor fix for ut
hhbyyh 7ee1c31
extends HashingTF
hhbyyh 12c2dc8
Merge remote-tracking branch 'upstream/master' into countVectorization
hhbyyh 99b0c14
undo extension from HashingTF
hhbyyh 1deca28
Merge remote-tracking branch 'upstream/master' into countVectorization
hhbyyh 576728a
rename to model and some fix
hhbyyh 24728e4
style improvement
hhbyyh 5f3f655
text change
hhbyyh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
82 changes: 82 additions & 0 deletions
82
mllib/src/main/scala/org/apache/spark/ml/feature/CountVectorizerModel.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
/* | ||
* 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.Experimental | ||
import org.apache.spark.ml.UnaryTransformer | ||
import org.apache.spark.ml.param.{ParamMap, ParamValidators, IntParam} | ||
import org.apache.spark.ml.util.Identifiable | ||
import org.apache.spark.mllib.linalg.{Vectors, VectorUDT, Vector} | ||
import org.apache.spark.sql.types.{StringType, ArrayType, DataType} | ||
|
||
/** | ||
* :: Experimental :: | ||
* Converts a text document to a sparse vector of token counts. | ||
* @param vocabulary An Array over terms. Only the terms in the vocabulary will be counted. | ||
*/ | ||
@Experimental | ||
class CountVectorizerModel (override val uid: String, val vocabulary: Array[String]) | ||
extends UnaryTransformer[Seq[String], Vector, CountVectorizerModel] { | ||
|
||
def this(vocabulary: Array[String]) = | ||
this(Identifiable.randomUID("countVectorizerModel"), vocabulary) | ||
|
||
/** | ||
* Corpus-specific filter to neglect scarce words in a document. For each document, terms with | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. neglect --> ignore |
||
* frequency (count) less than the given threshold are ignored. | ||
* Default: 1 | ||
* @group param | ||
*/ | ||
val minTermFreq: IntParam = new IntParam(this, "minTermFreq", | ||
"minimum frequency (count) filter used to neglect scarce words (>= 1). For each document, " + | ||
"terms with frequency less than the given threshold are ignored.", ParamValidators.gtEq(1)) | ||
|
||
/** @group setParam */ | ||
def setMinTermFreq(value: Int): this.type = set(minTermFreq, value) | ||
|
||
/** @group getParam */ | ||
def getMinTermFreq: Int = $(minTermFreq) | ||
|
||
setDefault(minTermFreq -> 1) | ||
|
||
override protected def createTransformFunc: Seq[String] => Vector = { | ||
val dict = vocabulary.zipWithIndex.toMap | ||
document => | ||
val termCounts = mutable.HashMap.empty[Int, Double] | ||
document.foreach { term => | ||
dict.get(term) match { | ||
case Some(index) => termCounts.put(index, termCounts.getOrElse(index, 0.0) + 1.0) | ||
case None => // ignore terms not in the vocabulary | ||
} | ||
} | ||
Vectors.sparse(dict.size, termCounts.filter(_._2 >= $(minTermFreq)).toSeq) | ||
} | ||
|
||
override protected def validateInputType(inputType: DataType): Unit = { | ||
require(inputType.sameType(ArrayType(StringType)), | ||
s"Input type must be ArrayType(StringType) but got $inputType.") | ||
} | ||
|
||
override protected def outputDataType: DataType = new VectorUDT() | ||
|
||
override def copy(extra: ParamMap): CountVectorizerModel = { | ||
val copied = new CountVectorizerModel(uid, vocabulary) | ||
copyValues(copied, extra) | ||
} | ||
} |
73 changes: 73 additions & 0 deletions
73
mllib/src/test/scala/org/apache/spark/ml/feature/CountVectorizorSuite.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
/* | ||
* 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 org.apache.spark.SparkFunSuite | ||
import org.apache.spark.ml.param.ParamsSuite | ||
import org.apache.spark.mllib.linalg.{Vector, Vectors} | ||
import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
import org.apache.spark.mllib.util.TestingUtils._ | ||
|
||
class CountVectorizerSuite extends SparkFunSuite with MLlibTestSparkContext { | ||
|
||
test("params") { | ||
ParamsSuite.checkParams(new CountVectorizerModel(Array("empty"))) | ||
} | ||
|
||
test("CountVectorizerModel common cases") { | ||
val df = sqlContext.createDataFrame(Seq( | ||
(0, "a b c d".split(" ").toSeq, | ||
Vectors.sparse(4, Seq((0, 1.0), (1, 1.0), (2, 1.0), (3, 1.0)))), | ||
(1, "a b b c d a".split(" ").toSeq, | ||
Vectors.sparse(4, Seq((0, 2.0), (1, 2.0), (2, 1.0), (3, 1.0)))), | ||
(2, "a".split(" ").toSeq, Vectors.sparse(4, Seq((0, 1.0)))), | ||
(3, "".split(" ").toSeq, Vectors.sparse(4, Seq())), // empty string | ||
(4, "a notInDict d".split(" ").toSeq, | ||
Vectors.sparse(4, Seq((0, 1.0), (3, 1.0)))) // with words not in vocabulary | ||
)).toDF("id", "words", "expected") | ||
val cv = new CountVectorizerModel(Array("a", "b", "c", "d")) | ||
.setInputCol("words") | ||
.setOutputCol("features") | ||
val output = cv.transform(df).collect() | ||
output.foreach { p => | ||
val features = p.getAs[Vector]("features") | ||
val expected = p.getAs[Vector]("expected") | ||
assert(features ~== expected absTol 1e-14) | ||
} | ||
} | ||
|
||
test("CountVectorizerModel with minTermFreq") { | ||
val df = sqlContext.createDataFrame(Seq( | ||
(0, "a a a b b c c c d ".split(" ").toSeq, Vectors.sparse(4, Seq((0, 3.0), (2, 3.0)))), | ||
(1, "c c c c c c".split(" ").toSeq, Vectors.sparse(4, Seq((2, 6.0)))), | ||
(2, "a".split(" ").toSeq, Vectors.sparse(4, Seq())), | ||
(3, "e e e e e".split(" ").toSeq, Vectors.sparse(4, Seq()))) | ||
).toDF("id", "words", "expected") | ||
val cv = new CountVectorizerModel(Array("a", "b", "c", "d")) | ||
.setInputCol("words") | ||
.setOutputCol("features") | ||
.setMinTermFreq(3) | ||
val output = cv.transform(df).collect() | ||
output.foreach { p => | ||
val features = p.getAs[Vector]("features") | ||
val expected = p.getAs[Vector]("expected") | ||
assert(features ~== expected absTol 1e-14) | ||
} | ||
} | ||
} | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just noticed this: we generally use very short uid names. How about "cntVec"?