Spark ML中的UnaryTransformer源码解析
目录
1. 源码加上中文注释
/**
* :: DeveloperApi ::
* 抽象类,用于接收一个输入列,应用转换并将结果作为新列输出。
*/
@DeveloperApi
abstract class UnaryTransformer[IN, OUT, T <: UnaryTransformer[IN, OUT, T]]
extends Transformer with HasInputCol with HasOutputCol with Logging {
/** @group setParam */
def setInputCol(value: String): T = set(inputCol, value).asInstanceOf[T]
/** @group setParam */
def setOutputCol(value: String): T = set(outputCol, value).asInstanceOf[T]
/**
* 使用给定的参数映射创建转换函数。输入的参数映射已经考虑了嵌入的参数映射。
* 因此,参数值应该完全由输入的参数映射确定。
*/
protected def createTransformFunc: IN => OUT
/**
* 返回输出列的数据类型。
*/
protected def outputDataType: DataType
/**
* 验证输入类型。如果无效,则抛出异常。
*/
protected def validateInputType(inputType: DataType): Unit = {}
override def transformSchema(schema: StructType): StructType = {
val inputType = schema($(inputCol)).dataType
validateInputType(inputType)
if (schema.fieldNames.contains($(outputCol))) {
throw new IllegalArgumentException(s"Output column ${$(outputCol)} already exists.")
}
val outputFields = schema.fields :+
StructField($(outputCol), outputDataType, nullable = false)
StructType(outputFields)
}
override def transform(dataset: Dataset[_]): DataFrame = {
transformSchema(dataset.schema, logging = true)
val transformUDF = udf(this.createTransformFunc, outputDataType)
dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
}
override def copy(extra: ParamMap): T = defaultCopy(extra)
}
2. 多种主要用法及其代码示例
- 设置输入列:
val transformer = new MyUnaryTransformer().setInputCol("input")
- 设置输出列:
val transformer = new MyUnaryTransformer().setOutputCol("output")
- 自定义转换函数:
class MyUnaryTransformer extends UnaryTransformer[String, Int, MyUnaryTransformer] {
override protected def createTransformFunc: String => Int = { input =>
// 自定义的转换逻辑,将字符串转换为整数
input.toInt
}
override protected def outputDataType: DataType = IntegerType
}
3. 源码适用场景
UnaryTransformer
是Spark ML中的抽象类,用于接收一个输入列,应用转换并将结果作为新列输出。它适用于以下场景:
- 需要对单个输入列进行转换操作,并将结果作为新列添加到数据集中。
- 需要自定义转换函数来处理特定的转换逻辑。