【发布时间】:2018-08-22 07:32:50
【问题描述】:
在创建ALS 模型时,我们可以提取一个userFactors DataFrame 和一个itemFactors DataFrame。这些 DataFrame 包含一个带有 Array 的列。
我想生成一些随机数据并将其合并到userFactors DataFrame。
这是我的代码:
val df1: DataFrame = Seq((123, 456, 4.0), (123, 789, 5.0), (234, 456, 4.5), (234, 789, 1.0)).toDF("user", "item", "rating")
val model1 = (new ALS()
.setImplicitPrefs(true)
.fit(df1))
val iF = model1.itemFactors
val uF = model1.userFactors
然后我使用 VectorAssembler 和这个函数创建一个随机 DataFrame:
def makeNew(df: DataFrame, rank: Int): DataFrame = {
var df_dummy = df
var i: Int = 0
var inputCols: Array[String] = Array()
for (i <- 0 to rank) {
df_dummy = df_dummy.withColumn("feature".concat(i.toString), rand())
inputCols = inputCols :+ "feature".concat(i.toString)
}
val assembler = new VectorAssembler()
.setInputCols(inputCols)
.setOutputCol("userFeatures")
val output = assembler.transform(df_dummy)
output.select("user", "userFeatures")
}
然后我使用新的用户 ID 创建 DataFrame 并添加随机向量和偏差:
val usersDf: DataFrame = Seq(567), (678)).toDF("user")
var usersFactorsNew: DataFrame = makeNew(usersDf, 20)
当我合并两个 DataFrame 时,问题就出现了。
usersFactorsNew.union(uF) 产生错误:
org.apache.spark.sql.AnalysisException: Union can only be performed on tables with the compatible column types. struct<type:tinyint,size:int,indices:array<int>,values:array<double>> <> array<float> at the second column of the second table;;
如果我打印架构,uF DataFrame 具有 Array[Float] 类型的特征向量,usersFactorsNew DataFrame 作为Vector 类型的特征向量。
我的问题是如何将Vector 的类型更改为数组以执行联合。
我尝试写这个udf,但收效甚微:
val toArr: org.apache.spark.ml.linalg.Vector => Array[Double] = _.toArray
val toArrUdf = udf(toArr)
也许VectorAssembler 不是此任务的最佳选择。但是,目前,这是我找到的唯一选择。我很想得到一些更好的建议。
【问题讨论】:
标签: arrays scala apache-spark dataframe vector