你可以使用SQLTransformer:
import org.apache.spark.ml.feature.SQLTransformer
val emptyRemover = new SQLTransformer().setStatement(
"SELECT * FROM __THIS__ WHERE size(words) > 0"
)
可以直接申请
val df = Seq(
("a the", Seq("the")), ("a of the", Seq()),
("big small", Seq("big", "small"))
).toDF("text", "words")
emptyRemover.transform(df).show
+---------+------------+
| text| words|
+---------+------------+
| a the| [the]|
|big small|[big, small]|
+---------+------------+
或用于Pipeline。
不过,在 Spark ML 流程中使用它之前,我会考虑两次。通常下游使用的工具,如CountVectorizer,可以很好地处理空输入:
import org.apache.spark.ml.feature.CountVectorizer
val vectorizer = new CountVectorizer()
.setInputCol("words")
.setOutputCol("features")
+---------+------------+-------------------+
| text| words| features|
+---------+------------+-------------------+
| a the| [the]| (3,[2],[1.0])|
| a of the| []| (3,[],[])|
|big small|[big, small]|(3,[0,1],[1.0,1.0])|
+---------+------------+-------------------+
并且某些词不存在,通常可以提供有用的信息。