(knn)行计算在pyspark上使用外部Dataframe

sqyvllje  于 2021-05-27  发布在  Spark
关注(0)|答案(0)|浏览(298)

问题
我的数据结构如下:

  1. train_info:(over 30000 rows)
  2. ----------
  3. odt:string (unique)
  4. holiday_type:string
  5. od_label:string
  6. array:array<double> (with variable length depend on different odt and holiday_type )
  7. useful_index:array<int> (length same as vectors)
  8. ...(other not important cols)
  9. label_data:(over 40000 rows)
  10. ----------
  11. holiday_type:string
  12. od_label: string
  13. l_origin_array:array<double> (with variable length)
  14. ...(other not important cols)
  15. my expected result is like this(length same with train_info):
  16. --------------
  17. odt:string
  18. holiday_label:string
  19. od_label:string
  20. prediction:int

我的解决方案如下:

  1. if __name__=='__main __'
  2. loop_item = train_info.collect()
  3. result = knn_for_loop(spark, loop_item,train_info.schema,label_data)
  4. ----- do something -------
  1. def knn_for_loop(spark, predict_list, schema, label_data):
  2. result = list()
  3. for i in predict_list:
  4. # turn this Row col to Data Frame and join on label data
  5. # across to this row data pick label data array data
  6. predict_df = spark.sparkContext.parallelize([i]).toDF(schema) \
  7. .join(label_data, on=['holiday_type', "od_label"], how='left') \
  8. .withColumn("l_array",
  9. UDFuncs.value_from_array_by_index(f.col('l_origin_array'), f.col("useful_index"))) \
  10. .toPandas()
  11. # pandas execute
  12. train_x = predict_df.l_array.values
  13. train_y = predict_df.label.values
  14. test_x = predict_df.array.values[0]
  15. test_y = KNN(train_x, train_y, test_x)
  16. result.append((i['odt'], i['holiday_type'], i['od_label'], test_y))
  17. return result

它的工作,但真的很慢,我估计每行需要18秒。
在r语言中,我可以很容易地使用do函数:
列车信息%>%分组依据(odt)%>%do(,knn循环,标签数据)
我尝试的东西
我尝试在使用前连接它们,在计算时查询它们,但数据太大,无法运行(连接后这两个df有4亿行,占用了配置单元上180gb的磁盘空间,查询速度非常慢)。我试着使用它,但它只允许一个pd.data.frame参数(慢)。
我尝试使用udf,但udf无法接收Dataframe对象。
我试图使用spark knn包,但我运行时出错,可能是我的脱机安装错误。
谢谢你的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题