spark 操作map中执行self.方法报错

python 复制代码
class model(object):
    def __init__(self):
        self.data = sc.textFile('path/to/data.csv')
        # other misc setup
    def run_model(self):
        self.data = self.data.map(self.transformation_function)
    def transformation_function(self,row):
        row = row.split(',')
        return row[0]+row[1]
test = model()
test.run_model()
test.data.take(10)

在pyspark中调用类方法,报错

Could not serialize object: Exception: It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.
原因

spark不允许在action或transformation中访问SparkContext,如果你的action或transformation中引用了self,那么spark会将整个对象进行序列化,并将其发到工作节点上,来确保每个执行任务的节点都能够访问到该方法以及它所依赖的类实例状态,但是序列化有一个限制,那就是不是所有的对象都可以被序列化。例如,SparkContext、SparkSession、打开的文件句柄、数据库连接等都不能被序列化,因为它们通常绑定到特定的运行环境,无法在网络上传输或在远程节点上复原。spark把对象序列化时这其中就保留了SparkContext,即使没有显式的访问它,它也会在闭包内被引用,所以会出错。
解决

将调用的类方法定义为静态方法 @staticmethod

python 复制代码
class model(object):
    @staticmethod
    def transformation_function(row):
        row = row.split(',')
        return row[0]+row[1]

    def __init__(self):
        self.data = sc.textFile('some.csv')

    def run_model(self):
        self.data = self.data.map(model.transformation_function)
相关推荐
m0_738098022 分钟前
使用Python操作文件和目录(os, pathlib, shutil)
jvm·数据库·python
好家伙VCC4 分钟前
# 发散创新:用 Rust构建高性能游戏日系统,从零实现事件驱动架构 在现代游戏开发中,**性能与可扩展性**是核心命题。传统基于
java·python·游戏·架构·rust
小璐资源网12 分钟前
Java 21 新特性实战:虚拟线程详解
java·开发语言·python
2301_8194143031 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
WZTTMoon32 分钟前
从互斥锁到无锁,Java 20年并发安全进化史
java·python·安全
Sakuraba Ema1 小时前
从零理解 MoE(Mixture of Experts)混合专家:原理、数学、稀疏性、专家数量影响与手写 PyTorch 实现
人工智能·pytorch·python·深度学习·数学·llm·latex
嫂子的姐夫1 小时前
041-全扣补环境:同花顺
爬虫·python·js逆向·逆向
2401_894241921 小时前
机器学习与人工智能
jvm·数据库·python
vx-程序开发1 小时前
springboot在线装修管理系统-计算机毕业设计源码56278
java·c语言·spring boot·python·spring·django·php