也许只是因为我对API比较陌生,但我觉得Spark ML方法经常返回不必要的难以使用的DF。
这一次,是ALS模型让我绊倒了。具体来说,推荐给所有用户方法。让我们重建它将返回的 DF 类型:
scala> val arrayType = ArrayType(new StructType().add("itemId", IntegerType).add("rating", FloatType))
scala> val recs = Seq((1, Array((1, .7), (2, .5))), (2, Array((0, .9), (4, .1)))).
toDF("userId", "recommendations").
select($"userId", $"recommendations".cast(arrayType))
scala> recs.show()
+------+------------------+
|userId| recommendations|
+------+------------------+
| 1|[[1,0.7], [2,0.5]]|
| 2|[[0,0.9], [4,0.1]]|
+------+------------------+
scala> recs.printSchema
root
|-- userId: integer (nullable = false)
|-- recommendations: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- itemId: integer (nullable = true)
| | |-- rating: float (nullable = true)
现在,我只关心recommendations
列中的itemId
。毕竟,这种方法recommendForAllUsers
不recommendAndScoreForAllUsers
(好吧好吧,我会停止时髦......
我该怎么做??
当我创建一个UDF时,我以为我有它:
scala> val itemIds = udf((arr: Array[(Int, Float)]) => arr.map(_._1))
但这会产生一个错误:
scala> recs.withColumn("items", items($"recommendations"))
org.apache.spark.sql.AnalysisException: cannot resolve 'UDF(recommendations)' due to data type mismatch: argument 1 requires array<struct<_1:int,_2:float>> type, however, '`recommendations`' is of array<struct<itemId:int,rating:float>> type.;;
'Project [userId#87, recommendations#92, UDF(recommendations#92) AS items#238]
+- Project [userId#87, cast(recommendations#88 as array<struct<itemId:int,rating:float>>) AS recommendations#92]
+- Project [_1#84 AS userId#87, _2#85 AS recommendations#88]
+- LocalRelation [_1#84, _2#85]
有什么想法吗?谢谢!
哇,我的同事想出了一个非常优雅的解决方案:
scala> recs.select($"userId", $"recommendations.itemId").show
+------+------+
|userId|itemId|
+------+------+
| 1|[1, 2]|
| 2|[0, 4]|
+------+------+
所以也许Spark ML API并不是那么困难:)
以数组作为列的类型,例如 recommendations
,使用爆炸函数(或更高级的平面地图运算符)会非常高效。
爆炸(e:列):列 为给定数组或映射列中的每个元素创建一个新行。
这为您提供了可以使用的裸露结构。
import org.apache.spark.sql.types._
val structType = new StructType().
add($"itemId".int).
add($"rating".float)
val arrayType = ArrayType(structType)
val recs = Seq((1, Array((1, .7), (2, .5))), (2, Array((0, .9), (4, .1)))).
toDF("userId", "recommendations").
select($"userId", $"recommendations" cast arrayType)
val exploded = recs.withColumn("recs", explode($"recommendations"))
scala> exploded.show
+------+------------------+-------+
|userId| recommendations| recs|
+------+------------------+-------+
| 1|[[1,0.7], [2,0.5]]|[1,0.7]|
| 1|[[1,0.7], [2,0.5]]|[2,0.5]|
| 2|[[0,0.9], [4,0.1]]|[0,0.9]|
| 2|[[0,0.9], [4,0.1]]|[4,0.1]|
+------+------------------+-------+
结构在运算符中很好select
带有*
(星形)将它们展平为每个结构字段的列。
你可以做select($"element.*")
.
scala> exploded.select("userId", "recs.*").show
+------+------+------+
|userId|itemId|rating|
+------+------+------+
| 1| 1| 0.7|
| 1| 2| 0.5|
| 2| 0| 0.9|
| 2| 4| 0.1|
+------+------+------+
我认为这可以做你所追求的。
p.s. 尽可能长时间地远离UDF,因为它们"触发"从内部格式(InternalRow
)到JVM对象的行转换,这可能导致过多的GC。