English 中文(简体)
模拟培训员关于最终到到期的铁路项目——类型Error: 启动_model_training() 缺失4项要求的立场论点
原标题:Model Trainer Issue on End-to-End ML Project - TypeError: initiate_model_training() missing 4 required positional arguments

我正在跟踪。 克利斯·纳基克的YouTube频道上的 Wine质量预测终端至EndML项目,以实施飞行远预测项目。

我在04_model_training.ipynb:

try:
    config = ConfigurationManager()
    model_trainer_config = config.get_model_trainer_config()
    model_trainer_config = ModelTrainer(model_trainer_config)
    # model_trainer_config.train()
    model_trainer_config.initiate_model_training()
except Exception as e:
    raise e

我发现这一错误:

TypeError: initiate_model_training() missing 4 required positional arguments:  X_train ,  X_test ,  y_train , and  y_test 

这里是全面的追溯:

[2023-12-16 21:58:22,484: INFO: common: yaml file: configconfig.yaml loaded successfully]
[2023-12-16 21:58:22,493: INFO: common: yaml file: params.yaml loaded successfully]
[2023-12-16 21:58:22,493: INFO: common: yaml file: schema.yaml loaded successfully]
[2023-12-16 21:58:22,493: INFO: common: created directory at: artifacts]
[2023-12-16 21:58:22,493: INFO: common: created directory at: artifacts/model_trainer]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[25], line 8
      6     model_trainer_config.initiate_model_training()
      7 except Exception as e:
----> 8     raise e

Cell In[25], line 6
      4     model_trainer_config = ModelTrainer(model_trainer_config)
      5     # model_trainer_config.train()
----> 6     model_trainer_config.initiate_model_training()
      7 except Exception as e:
      8     raise e

TypeError: initiate_model_training() missing 4 required positional arguments:  X_train ,  X_test ,  y_train , and  y_test 

以下是<代码>ModelTrainer类别:

class ModelTrainer:

    def __init__(self, model_trainer_config):
        self.model_trainer_config = model_trainer_config  
    # def __init__(self):
        # self.model_trainer_config = ModelTrainerConfig()    


    def save_obj(file_path, obj):
        try:

            dir_path = os.path.dirname(file_path)
            os.makedirs(dir_path, exist_ok=True)

            with open(file_path,  wb ) as file_obj:
                joblib.dump(obj, file_obj, compress= ( gzip ))

        except Exception as e:
            logger.info( Error occured in utils save_obj )
            raise e
        

    def evaluate_model(X_train, y_train, X_test, y_test, models):

        try:
            report = {}
            for i in range(len(models)):

                model = list(models.values())[i]

                # Train model
                model.fit(X_train,y_train)

                # Predict Testing data
                y_test_pred = model.predict(X_test)

                # Get R2 scores for train and test data
                test_model_score = r2_score(y_test,y_test_pred)

                report[list(models.keys())[i]] =  test_model_score

            return report

        except Exception as e:
            logger.info( Exception occured during model training )
            raise e    



    def initiate_model_training(self, X_train, X_test, y_train, y_test):
        try:
            logger.info( Splitting  )

            models={
             LinearRegression :LinearRegression(),
             Lasso :Lasso(),
             Ridge :Ridge(),
             Elasticnet :ElasticNet(),
             RandomForestRegressor : RandomForestRegressor(),
             GradientBoostRegressor()  : GradientBoostingRegressor(),
            "AdaBoost" : AdaBoostRegressor(),
             DecisionTreeRegressor  : DecisionTreeRegressor(),
            "SupportVectorRegressor" : SVR(),
            "KNN" : KNeighborsRegressor()
            }

            model_report:dict = ModelTrainer.evaluate_model(X_train,y_train, X_test, y_test, models)
            print(model_report)
            print("
====================================================================================")
            logger.info(f Model Report : {model_report} )

            # to get best model score from dictionary
            best_model_score = max(sorted(model_report.values()))

            best_model_name = list(model_report.keys())[
                list(model_report.values()).index(best_model_score)
            ]

            best_model = models[best_model_name]

            print(f"Best Model Found, Model Name :{best_model_name}, R2-score: {best_model_score}")
            print("
====================================================================================")
            logger.info(f"Best Model Found, Model name: {best_model_name}, R2-score: {best_model_score}")
            logger.info(f"{best_model.feature_names_in_}")
            
            ModelTrainer.save_obj(
            file_path = self.model_trainer_config.trained_model_file_path,
            obj = best_model
            )

        except Exception as e:
            logger.info( Exception occured at model trianing )
            raise e

http://github.com/MdEhsanulHaqueKanan/Flight-Fare-Prediction-End-to-End-ML-project/blob/main/research/04_model_training.ipynb”rel=“nofollow noreferer” 我的档案载于Gite Hub

我的卷宗编码是UTF-8

请帮助我解决这一问题吗?

问题回答

因此,根据您在《jupyter notebook》中的逻辑,您可能已经修改了 初始_model_training(<>/code>,以类似以下功能:

    def initiate_model_training(self): # removing the required variables to be passed into the function because those variables are created below (assuming they were correctly generated in train() )
        # lines below taken from your commented out train() function
        train_data = pd.read_csv(self.config.train_data_path)
        test_data = pd.read_csv(self.config.test_data_path)

        X_train = train_data.drop([self.config.target_column], axis=1)
        X_test = test_data.drop([self.config.target_column], axis=1)
        y_train = train_data[[self.config.target_column]]
        y_test = test_data[[self.config.target_column]]
        # lines above taken from your commented out train() function

        try:
            logger.info( Splitting  )

            models={
             LinearRegression :LinearRegression(),
             Lasso :Lasso(),
             Ridge :Ridge(),
             Elasticnet :ElasticNet(),
             RandomForestRegressor : RandomForestRegressor(),
             GradientBoostRegressor()  : GradientBoostingRegressor(),
            "AdaBoost" : AdaBoostRegressor(),
             DecisionTreeRegressor  : DecisionTreeRegressor(),
            "SupportVectorRegressor" : SVR(),
            "KNN" : KNeighborsRegressor()
            }

            model_report:dict = ModelTrainer.evaluate_model(X_train,y_train, X_test, y_test, models)
            print(model_report)
            print("
====================================================================================")
            logger.info(f Model Report : {model_report} )

            # to get best model score from dictionary
            best_model_score = max(sorted(model_report.values()))

            best_model_name = list(model_report.keys())[
                list(model_report.values()).index(best_model_score)
            ]

            best_model = models[best_model_name]

            print(f"Best Model Found, Model Name :{best_model_name}, R2-score: {best_model_score}")
            print("
====================================================================================")
            logger.info(f"Best Model Found, Model name: {best_model_name}, R2-score: {best_model_score}")
            logger.info(f"{best_model.feature_names_in_}")
            
            ModelTrainer.save_obj(
            file_path = self.model_trainer_config.trained_model_file_path,
            obj = best_model
            )

        except Exception as e:
            logger.info( Exception occured at model trianing )
            raise e

您应研究并了解这些网站:https://drive.google.com/file/d/1c7k8i1l2X_r9i4yWAkzxiP1QNu8_wqap/。 在你开始修改法典之前,这些档案(从你下面的辅导处)。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...