如何在MLLIB pipeline中串联Spark NLP的Stemmer与SparkML的CountVectorizer
MLLIB Pipeline串联Spark NLP Stemmer与CountVectorizer问题解决方案
报错根因
Spark NLP的所有标注组件(包含Stemmer)的输出列均为Spark NLP专属Annotation结构体数组,而Spark ML提供的CountVectorizer仅接受array<string>类型的纯文本序列作为输入,二者类型不匹配导致类型校验失败。
修复步骤
- 在Stemmer与CountVectorizer之间新增Spark NLP的
Finisher组件,该组件的作用是将Annotation结构体中的文本结果提取出来,转换为原生Spark数据类型 - 配置
Finisher的setOutputAsArray参数为true,保证输出结果为array<string>格式,匹配CountVectorizer的输入要求 - 将
Finisher的输出列设置为CountVectorizer的输入列,再按顺序组装Pipeline即可
代码示例(Scala)
// 定义Stemmer val stemmer = new Stemmer() .setInputCols("token") .setOutputCol("stem") // 定义Finisher做类型转换 val stemFinisher = new Finisher() .setInputCols("stem") .setOutputCols("stem_arr") .setOutputAsArray(true) // 输出为array<string> .setCleanAnnotations(true) // 可选:清理不需要的中间Annotation列节省资源 // 定义CountVectorizer,输入为Finisher输出的字符串数组 val countVectorizer = new CountVectorizer() .setInputCol("stem_arr") .setOutputCol("count_features") // 按顺序组装Pipeline val pipeline = new Pipeline() .setStages(Array( /* 前置组件:如DocumentAssembler、Tokenizer等 */ stemmer, stemFinisher, countVectorizer ))
内容的提问来源于stack exchange,提问作者Benjamin
相关产品推荐
相关产品推荐

