如何在数据帧中跨组之间使用线性重试



让我们说我的Spark DataFrame(DF(看起来像

id | age | earnings| health 
----------------------------
1  | 34  | 65      | 8
2  | 65  | 12      | 4
2  | 20  | 7       | 10
1  | 40  | 75      | 7
.  | ..  | ..      | ..

我想分组DF,应用一个函数(例如线性回归取决于多个列 - 在这种情况下两列 - 在每个聚合的DF上的汇总DF(,并像

一样获取输出
id | intercept| slope 
----------------------
1  |   ?      |  ? 
2  |   ?      |  ? 
from sklearn.linear_model import LinearRegression
lr_object = LinearRegression()
def linear_regression(ith_DF):
    # Note: for me it is necessary that ith_DF should contain all 
    # data within this function scope, so that I can apply any 
    # function that needs all data in ith_DF
    X = [i.earnings for i in ith_DF.select("earnings").rdd.collect()]
    y = [i.health for i in ith_DF.select("health").rdd.collect()]
    lr_object.fit(X, y)
    return lr_object.intercept_, lr_object.coef_[0]
coefficient_collector = []
# following iteration is not possible in spark as 'GroupedData' 
# object is not iterable, please consider it as pseudo code
for ith_df in df.groupby("id"): 
    c, m = linear_regression(ith_df)
    coefficient_collector.append((float(c), float(m)))
model_df = spark.createDataFrame(coefficient_collector, ["intercept", "slope"])
model_df.show()

我认为这可以完成,因为使用pandas_udf Spark 2.3。实际上,有一个示例是在此处发布pandas_udfs的分组回归:

为python介绍pandas udf

我要做的是filter创建较小数据框并进行处理的主要数据框架,例如线性回归。

然后,您可以并行执行线性回归(在使用相同的SparkSession上的线程安全性(和主要数据帧加缓存的线性回归。

应该赋予您火花的全部力量。

P.S。我对Spark的那部分的有限理解使我认为在Spark Mllib和TensorFrames中使用了非常相似的方法,也是" Scala和Apache Spark的实验性TensorFlow绑定"。

最新更新