pyspark 小知识——自定义聚合函数UDAF:使用pyspark分组计算AUC

本文介绍了在pyspark中如何利用自定义函数(UDF)来实现类似自定义聚合函数(UDAF)的效果,特别是在计算AUC场景下。由于pyspark官方未提供直接计算AUC的聚合函数,作者分享了在金融场景中,如何通过UDF按时间分组计算模型性能的AUC,并提到了这种方式在小数据量下是可行的,但效率可能不如真正的UDAF。
摘要由CSDN通过智能技术生成

在pyspark中,自定义聚合函数UDAF,在实现上有些困难,但是我们可以用另外一种方法实现同样的功能:利用自定义函数UDF,实现自定义聚合函数UDAF的功能(PS:虽然能实现同样的功能,但速度上可能不及真正的UDAF,但是小数据量没问题)。

在网上搜寻资料的时候,发现关于这方面的资料非常少,并且pyspark UDF在使用上还是有很多坑的,现将自己的使用心得和详细的注意事项记录下来,供大家参考。

使用场景示例
金融场景中,在对信用模型进行效果分析的时候,需要查看该模型分在各个月份上的性能,具体操作是:使用时间进行分组,然后求各个分组内,该模型分的AUC。

解决办法:由于在pyspark中,没有现成的用于计算AUC的聚合函数,所以需要自己定义。但是自定义聚合函数又比较困难,我们用另一种方式实现该功能。代码如下:

from pyspark.sql import SparkSession # SparkConf、SparkContext 和 SQLContext 都已经被封装在 SparkSession 
from pyspark.sql import functions as F 
from pyspark.sql import Window
from pyspark.sql import Row 
Build machine learning models, natural language processing applications, and recommender systems with PySpark to solve various business challenges. This book starts with the fundamentals of Spark and its evolution and then covers the entire spectrum of traditional machine learning algorithms along with natural language processing and recommender systems using PySpark. Machine Learning with PySpark shows you how to build supervised machine learning models such as linear regression, logistic regression, decision trees, and random forest. You'll also see unsupervised machine learning models such as K-means and hierarchical clustering. A major portion of the book focuses on feature engineering to create useful features with PySpark to train the machine learning models. The natural language processing section covers text processing, text mining, and embedding for classification. After reading this book, you will understand how to use PySpark's machine learning library to build and train various machine learning models. Additionally you'll become comfortable with related PySpark components, such as data ingestion, data processing, and data analysis, that you can use to develop data-driven intelligent applications. What You Will Learn Build a spectrum of supervised and unsupervised machine learning algorithms Implement machine learning algorithms with Spark MLlib libraries Develop a recommender system with Spark MLlib libraries Handle issues related to feature engineering, class balance, bias and variance, and cross validation for building an optimal fit model Who This Book Is For Data science and machine learning professionals.
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值