AWS Lambda 上管道的 Unpickle 失败

Unpickle of a pipeline fail on AWS Lambda

首先,很抱歉,如果解决方案已经发布,我看了很多帖子,没有找到解决这个问题的方法

我有一个 Python class 在我的机器上运行良好,以便训练 + 运行 一个 ML 模型。

我想在 AWS Lambda 上执行 运行(并且只执行 运行),但它在 pickle.load 期间失败,因为它似乎找不到管道(虽然它们在代码中可用)

"Can't get attribute 'myMLClass' on <module 'main' from '/var/runtime/awslambda/bootstrap.py'>", "errorType": "AttributeError"

代码在 Python 3.6 中,它使用 sklearn 管道、XGBOOST 和 Pickle 到 save/load 模型。

这里是它的概述:

import stuff

class myMLClass:

    def myTransformation(self, dataframe): 
        #myTransformations

    def train_model(self)
        preprocessor = FunctionTransformer(myTransformation, validate=False)
        xgb = XGBClassifier()
        pipeline_xgb = make_pipeline(preprocessor, xgb)
        #[XGB Stuff: fit, predict,...]
        with open("myTrainedPipeline.pkl", 'wb') as file:
            pickle.dump(pipeline_xgb, file)

    def run_model(self)
        with open("myTrainedPipeline.pkl", 'rb') as file:
            pipeline = pickle.load(file)    ==> Which trigger the error

def main():
    myObject = myMLClass("DEV")
    myObject.run_model()

同样,同样的 class 在我的机器上用于训练和 运行ning 都工作正常。我知道 Pickle 不会序列化转换函数,而只是对它的引用,这就是为什么我在相同的 class

下包含了训练和 运行nning 操作

注意: 如果我尝试从 main() 函数中解开,问题是相同的

非常感谢您的帮助!

亚历克斯

仅供参考,由于此页面的解释,我能够解决这个问题:

https://www.stefaanlippens.net/python-pickling-and-dealing-with-attributeerror-module-object-has-no-attribute-thing.html

基本上,我需要将主文件和模块分成两个不同的文件。

我认为这是因为 AWS Lambda 的工作方式,尤其是 bootstrap.py。拆分后,代理明确需要导入专用模块,因为导入是在 main

中声明的