-
Notifications
You must be signed in to change notification settings - Fork 28.2k
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
[ML][FEATURE] SPARK-5566: RegEx Tokenizer #4504
Changes from 21 commits
01cd26f
9547e9d
9e07a78
9f8685a
11ca50f
196cd7a
2e89719
77ff9ca
7f930bb
f6a5002
19f9e53
9082fc3
d3ef6d3
cb9c9a7
201a107
132b00b
cd6642e
e262bac
b66313f
38b95a1
6a85982
daf685e
12dddb4
148126f
e88d7b8
2338da5
f96526d
9651aec
556aa27
a164800
5f09434
cb07021
716d257
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,7 +19,7 @@ package org.apache.spark.ml.feature | |
|
||
import org.apache.spark.annotation.AlphaComponent | ||
import org.apache.spark.ml.UnaryTransformer | ||
import org.apache.spark.ml.param.ParamMap | ||
import org.apache.spark.ml.param.{ParamMap, IntParam, BooleanParam, Param} | ||
import org.apache.spark.sql.types.{DataType, StringType, ArrayType} | ||
|
||
/** | ||
|
@@ -39,3 +39,67 @@ class Tokenizer extends UnaryTransformer[String, Seq[String], Tokenizer] { | |
|
||
override protected def outputDataType: DataType = new ArrayType(StringType, false) | ||
} | ||
|
||
/** | ||
* :: AlphaComponent :: | ||
* A regex based tokenizer that extracts tokens either by repeatedly matching the regex(default) | ||
* or using it to split the text (set matching to false). Optional parameters also allow to fold | ||
* the text to lowercase prior to it being tokenized and to filer tokens using a minimal length. | ||
* It returns an array of strings that can be empty. | ||
* The default parameters are regex = "\\p{L}+|[^\\p{L}\\s]+", matching = true, | ||
* lowercase = false, minTokenLength = 1 | ||
*/ | ||
@AlphaComponent | ||
class RegexTokenizer extends UnaryTransformer[String, Seq[String], RegexTokenizer] { | ||
|
||
/** | ||
* param for minimum token length, default is one to avoid returning empty strings | ||
* @group param | ||
*/ | ||
val minTokenLength = new IntParam(this, "minLength", "minimum token length", Some(1)) | ||
|
||
/** @group setParam */ | ||
def setMinTokenLength(value: Int) = set(minTokenLength, value) | ||
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.
|
||
|
||
/** @group getParam */ | ||
def getMinTokenLength: Int = get(minTokenLength) | ||
|
||
/** | ||
* param sets regex as splitting on gaps (true) or matching tokens (false) | ||
* @group param | ||
*/ | ||
val gaps = new BooleanParam(this, "gaps", "Set regex to match gaps or tokens", Some(false)) | ||
|
||
/** @group setParam */ | ||
def setGaps(value: Boolean) = set(gaps, value) | ||
|
||
/** @group getParam */ | ||
def getGaps: Boolean = get(gaps) | ||
|
||
/** | ||
* param sets regex pattern used by tokenizer | ||
* @group param | ||
*/ | ||
val pattern = new Param(this, "pattern", | ||
"regex pattern used for tokenizing", Some("\\p{L}+|[^\\p{L}\\s]+".r)) | ||
|
||
/** @group setParam */ | ||
def setPattern(value: String) = set(pattern, value.r) | ||
|
||
/** @group getParam */ | ||
def getPattern: String = get(pattern).toString | ||
|
||
override protected def createTransformFunc(paramMap: ParamMap): String => Seq[String] = { str => | ||
|
||
val re = paramMap(pattern) | ||
val tokens = if(paramMap(gaps)) re.split(str).toList else (re.findAllIn(str)).toList | ||
|
||
tokens.filter(_.length >= paramMap(minTokenLength)) | ||
} | ||
|
||
override protected def validateInputType(inputType: DataType): Unit = { | ||
require(inputType == StringType, s"Input type must be string type but got $inputType.") | ||
} | ||
|
||
override protected def outputDataType: DataType = new ArrayType(StringType, false) | ||
} |
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 java.util.Arrays; | ||||||
import java.util.List; | ||||||
|
||||||
import org.junit.After; | ||||||
import org.junit.Assert; | ||||||
import org.junit.Before; | ||||||
import org.junit.Test; | ||||||
|
||||||
import org.apache.spark.api.java.JavaRDD; | ||||||
import org.apache.spark.api.java.JavaSparkContext; | ||||||
import org.apache.spark.sql.DataFrame; | ||||||
import org.apache.spark.sql.Row; | ||||||
import org.apache.spark.sql.SQLContext; | ||||||
|
||||||
public class JavaTokenizerSuite { | ||||||
private transient JavaSparkContext jsc; | ||||||
private transient SQLContext jsql; | ||||||
|
||||||
@Before | ||||||
public void setUp() { | ||||||
jsc = new JavaSparkContext("local", "JavaTokenizerSuite"); | ||||||
jsql = new SQLContext(jsc); | ||||||
} | ||||||
|
||||||
@After | ||||||
public void tearDown() { | ||||||
jsc.stop(); | ||||||
jsc = null; | ||||||
} | ||||||
|
||||||
@Test | ||||||
public void RegexTokenizer() { | ||||||
RegexTokenizer myRegExTokenizer = new RegexTokenizer() | ||||||
.setInputCol("rawText") | ||||||
.setOutputCol("tokens") | ||||||
.setPattern("\\s") | ||||||
.setGaps(true) | ||||||
.setMinTokenLength(0); | ||||||
|
||||||
List<String> t = Arrays.asList( | ||||||
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. Unit tests should be minimal. Pulling in JSON RDD is not necessary. Please check how spark/examples/src/main/scala/org/apache/spark/examples/ml/SimpleTextClassificationPipeline.scala Line 29 in 4a17eed
spark/examples/src/main/java/org/apache/spark/examples/ml/JavaCrossValidatorExample.java Line 74 in 4a17eed
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. That was actually what I tried to do in the first place. |
||||||
"{\"rawText\": \"Test of tok.\", \"wantedTokens\": [\"Test\", \"of\", \"tok.\"]}", | ||||||
"{\"rawText\": \"Te,st. punct\", \"wantedTokens\": [\"Te,st.\",\"\",\"punct\"]}"); | ||||||
|
||||||
JavaRDD<String> myRdd = jsc.parallelize(t); | ||||||
DataFrame dataset = jsql.jsonRDD(myRdd); | ||||||
|
||||||
Row[] pairs = myRegExTokenizer.transform(dataset) | ||||||
.select("tokens","wantedTokens") | ||||||
.collect(); | ||||||
|
||||||
Assert.assertEquals(pairs[0].get(0), pairs[0].get(1)); | ||||||
Assert.assertEquals(pairs[1].get(0), pairs[1].get(1)); | ||||||
} | ||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
/* | ||
* 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.scalatest.FunSuite | ||
|
||
import org.apache.spark.SparkException | ||
import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
import org.apache.spark.sql.{DataFrame, Row, SQLContext} | ||
|
||
case class TextData(rawText : String, wantedTokens: Seq[String]) | ||
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. insert an empty line between class declarations. |
||
class TokenizerSuite extends FunSuite with MLlibTestSparkContext { | ||
|
||
@transient var sqlContext: SQLContext = _ | ||
|
||
override def beforeAll(): Unit = { | ||
super.beforeAll() | ||
sqlContext = new SQLContext(sc) | ||
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. initialize |
||
} | ||
|
||
test("RegexTokenizer"){ | ||
val myRegExTokenizer = new RegexTokenizer() | ||
.setInputCol("rawText") | ||
.setOutputCol("tokens") | ||
|
||
var dataset = sqlContext.createDataFrame( | ||
sc.parallelize(List( | ||
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. minor: |
||
TextData("Test for tokenization.",List("Test","for","tokenization",".")), | ||
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. space after |
||
TextData("Te,st. punct",List("Te",",","st",".","punct")) | ||
))) | ||
testRegexTokenizer(myRegExTokenizer,dataset) | ||
|
||
dataset = sqlContext.createDataFrame( | ||
sc.parallelize(List( | ||
TextData("Test for tokenization.",List("Test","for","tokenization")), | ||
TextData("Te,st. punct",List("punct")) | ||
))) | ||
myRegExTokenizer.asInstanceOf[RegexTokenizer] | ||
.setMinTokenLength(3) | ||
testRegexTokenizer(myRegExTokenizer,dataset) | ||
|
||
myRegExTokenizer.asInstanceOf[RegexTokenizer] | ||
.setPattern("\\s") | ||
.setGaps(true) | ||
.setMinTokenLength(0) | ||
dataset = sqlContext.createDataFrame( | ||
sc.parallelize(List( | ||
TextData("Test for tokenization.",List("Test","for","tokenization.")), | ||
TextData("Te,st. punct",List("Te,st.","","punct")) | ||
))) | ||
testRegexTokenizer(myRegExTokenizer,dataset) | ||
} | ||
|
||
test("Tokenizer") { | ||
val oldTokenizer = new Tokenizer() | ||
.setInputCol("rawText") | ||
.setOutputCol("tokens") | ||
var dataset = sqlContext.createDataFrame( | ||
sc.parallelize(List( | ||
TextData("Test for tokenization.",List("test","for","tokenization.")), | ||
TextData("Te,st. punct",List("te,st.","","punct")) | ||
))) | ||
testTokenizer(oldTokenizer,dataset) | ||
} | ||
|
||
def testTokenizer(t: Tokenizer,dataset: DataFrame): Unit = { | ||
t.transform(dataset) | ||
.select("tokens","wantedTokens") | ||
.collect().foreach{ | ||
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. space before |
||
case Row(tokens: Seq[Any], wantedTokens: Seq[Any]) => | ||
assert(tokens === wantedTokens) | ||
case e => | ||
throw new SparkException(s"Row $e should contain only tokens and wantedTokens columns") | ||
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.
.collect()
.foreach { case Row(actual, expected) =>
assert(actual === expected)
} |
||
} | ||
} | ||
|
||
def testRegexTokenizer(t: RegexTokenizer,dataset: DataFrame): Unit = { | ||
t.transform(dataset) | ||
.select("tokens","wantedTokens") | ||
.collect().foreach{ | ||
case Row(tokens: Seq[Any], wantedTokens: Seq[Any]) => | ||
assert(tokens === wantedTokens) | ||
case e => | ||
throw new SparkException(s"Row $e should contain only tokens and wantedTokens columns") | ||
} | ||
} | ||
|
||
} |
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.
Please append
: IntParam
tominTokenLength
. See SPARK-6428. Please also update other method declarations.