gpt4 book ai didi

scala - 当 udf 函数不接受足够大的输入变量时 Spark DataFrames

转载 作者:行者123 更新时间:2023-12-04 16:42:38 27 4
gpt4 key购买 nike

我正在准备一个带有 id 和我的特征向量的 DataFrame,以便稍后用于进行预测。我在我的数据框上做了一个 groupBy,在我的 groupBy 中,我将几列作为列表合并到一个新列中:

def mergeFunction(...) // with 14 input variables

val myudffunction( mergeFunction ) // Spark doesn't support this

df.groupBy("id").agg(
collect_list(df(...)) as ...
... // too many of these (something like 14 of them)
).withColumn("features_labels",
myudffunction(
col(...)
, col(...) )
.select("id", "feature_labels")

这就是我创建特征向量及其标签的方式。到目前为止,它一直在为我工作,但这是我使用这种方法的特征向量第一次变得大于数字 10,这是 Spark 中的 udf 函数最多接受的。

I am not sure how else I can fix this? Is the size of udf inputs in Spark going to get bigger, am have I understood them incorrectly, or there is a better way?

最佳答案

用户定义的函数最多可定义 22 个参数。仅限 udf helper 最多为 10 个参数定义。要处理具有大量参数的函数,您可以使用 org.apache.spark.sql.UDFRegistration .

例如

val dummy = ((
x0: Int, x1: Int, x2: Int, x3: Int, x4: Int, x5: Int, x6: Int, x7: Int,
x8: Int, x9: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int,
x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int) => 1)

货车注册:
import org.apache.spark.sql.expressions.UserDefinedFunction

val dummyUdf: UserDefinedFunction = spark.udf.register("dummy", dummy)

并直接使用
val df = spark.range(1)
val exprs = (0 to 21).map(_ => lit(1))

df.select(dummyUdf(exprs: _*))

或通过 callUdf 点名
import org.apache.spark.sql.functions.callUDF

df.select(
callUDF("dummy", exprs: _*).alias("dummy")
)

或 SQL 表达式:
df.selectExpr(s"""dummy(${Seq.fill(22)(1).mkString(",")})""")

您也可以创建 UserDefinedFunction目的:
import org.apache.spark.sql.expressions.UserDefinedFunction

Seq(1).toDF.select(UserDefinedFunction(dummy, IntegerType, None)(exprs: _*))

在实践中,具有 22 个参数的函数并不是很有用,除非您想使用 Scala 反射来生成这些参数,否则会有维护的噩梦。

我会考虑使用集合( arraymap )或 struct作为输入或将其分为多个模块。例如:
val aLongArray = array((0 to 256).map(_ => lit(1)): _*)

val udfWitharray = udf((xs: Seq[Int]) => 1)

Seq(1).toDF.select(udfWitharray(aLongArray).alias("dummy"))

关于scala - 当 udf 函数不接受足够大的输入变量时 Spark DataFrames,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39494620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com