Pyspark - 用于按两个日期列分组的 UDAF 函数,用于计算实际值和预测值之间的 RMSE 的 UDAF

Pyspark - UDAF function for a groupby two date columns, UDAF to calculate RMSE between actuals and predictions

在接下来的几年里,我在 pyspark 数据框中有这样的数据。 week_start_dt 是我开始预测的时候。 start_month 是前 12 个月。

+--------------------+------------------+----------------------+----------------+
|     start_month    |     week_start_dt|           predictions|       actuals  |
+--------------------+------------------+----------------------+----------------+
|             2019-01|        2019-11-11|                    12|              11|
|             2018-12|        2019-11-11|                    13|              11|
|             2019-08|        2019-11-11|                     9|              11|
|             2019-11|        2019-11-11|                    12|              11|
|             2019-11|        2019-11-11|                  1970|            1440|
|             2019-11|        2019-11-11|                   478|             501|
+--------------------+------------------+----------------------+----------------+

我想在 start_monthweek_start_dt 上用 groupby 计算 RMSE。我认为它需要一个用户定义的聚合函数。 pandas 中的一些内容:

我使用以下代码来汇总 groupby 的实际值和预测值。

df_startmonth_week = actuals_compare.groupby('start_month', 'week_start_dt').agg(f.sum('predictions'), f.sum('actuals'))

在计算预测值和实际值之间的 RMSE 时,我要在聚合步骤中更改什么?我需要 UDF 才能执行此操作吗?

这是我在 excel

中制定的最终目标的示例
| week_start_dt | start_month | RMSE |
|---------------|-------------|------|
| 20-01-2020    | 2019-02     | 2345 |
| 20-01-2020    | 2019-03     | 2343 |
| 20-01-2020    | 2019-04     | 2341 |
| 20-01-2020    | 2019-05     | 2100 |
| 20-01-2020    | 2019-06     | 1234 |

我看不出与 的区别,所以我将解决方案调整为略有不同的变量名称:

import pyspark.sql.functions as psf

def compute_RMSE(expected_col, actual_col):

  rmse = old_df.withColumn("squarederror",
                           psf.pow(psf.col(actual_col) - psf.col(expected_col),
                                   psf.lit(2)
                           ))
  .groupby('start_month', 'week_start_dt')
  .agg(psf.avg(psf.col("squarederror")).alias("mse"))
  .withColumn("rmse", psf.sqrt(psf.col("mse")))

  return(rmse)


compute_RMSE("predictions", "actuals")

如果我遗漏了问题的细微差别,请告诉我