ML项目模型训练器TypeError:构造函数参数不匹配问题诊断与解决

花韻仙語
发布: 2025-09-22 14:44:38
原创
1150人浏览过

ML项目模型训练器TypeError:构造函数参数不匹配问题诊断与解决

本文深入探讨了在端到端机器学习项目中常见的 TypeError: __init__() got an unexpected keyword argument 错误。该错误通常源于类构造函数(__init__ 方法)的参数定义与其实例化时传入的参数不一致。教程将通过具体案例,分析错误根源,并提供两种修正方案,包括调整配置类和模型训练器类的构造函数,以确保参数匹配,提升代码健壮性。

引言

在构建端到端机器学习项目时,模块化和清晰的代码结构至关重要。常见的模式是将配置管理、数据处理、模型训练等不同阶段封装到独立的类中。然而,在这些类之间传递数据或配置时,我们可能会遇到 typeerror: __init__() got an unexpected keyword argument 这样的错误。这个错误明确指出,你在实例化一个类时,传入了一个该类的 __init__ 方法并未定义的关键字参数。理解并解决这类问题是编写健壮python代码的基础。

问题分析:TypeError 的根源

根据提供的错误信息和堆跟踪,TypeError: __init__() got an unexpected keyword argument 'trained_model_file_path' 发生在 get_model_trainer_config() 方法内部,具体是在尝试实例化 ModelTrainerConfig 类时。

错误代码片段:

# 错误发生在 config.get_model_trainer_config() 内部
# 进一步追溯,是在 ModelTrainerConfig 实例化时
model_trainer_config = ModelTrainerConfig(
    root_dir=config.root_dir,
    train_data_path = config.train_data_path,
    test_data_path = config.test_data_path,
    trained_model_file_path =  os.path.join('artifact', 'model'), # 这一行导致错误
    model_name = config.model_name,
    alpha = params.alpha,
    l1_ratio = params.l1_ratio,
    target_column = schema.name
)
登录后复制

错误解释:

这个 TypeError 表明 ModelTrainerConfig 类的 __init__ 方法在定义时,并没有包含名为 trained_model_file_path 的参数。然而,在 get_model_trainer_config 方法中,我们试图以关键字参数的形式将 trained_model_file_path 传递给 ModelTrainerConfig 的构造函数。这种定义与调用之间的不匹配是导致 TypeError 的直接原因。

例如,如果 ModelTrainerConfig 的定义可能如下(缺少 trained_model_file_path):

# 假设 ModelTrainerConfig 的定义可能如下(导致错误)
# src/config/configuration.py 或其他地方
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class ModelTrainerConfig:
    root_dir: Path
    train_data_path: Path
    test_data_path: Path
    model_name: str
    alpha: float
    l1_ratio: float
    target_column: str
    # 缺少 trained_model_file_path
登录后复制

解决方案一:修正 ModelTrainerConfig 的构造函数

解决当前 TypeError 的最直接方法是修改 ModelTrainerConfig 类的定义,使其 __init__ 方法能够接受 trained_model_file_path 参数。

修正后的 ModelTrainerConfig 定义:

import os
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class ModelTrainerConfig:
    root_dir: Path
    train_data_path: Path
    test_data_path: Path
    trained_model_file_path: Path # 添加这一行以接受参数
    model_name: str
    alpha: float
    l1_ratio: float
    target_column: str
登录后复制

通过将 trained_model_file_path: Path 添加到 dataclass 的字段中,dataclass 会自动生成一个包含此参数的 __init__ 方法,从而消除 TypeError。如果不是使用 dataclass,而是手动定义 __init__ 方法,则需要确保 __init__ 方法签名中包含 trained_model_file_path。

解决方案二:调整 ModelTrainer 类的构造函数(基于最佳实践)

虽然上述修正解决了 TypeError,但原始问题和答案中也提到了 ModelTrainer 类的实例化方式。尽管这不是导致当前 TypeError 的直接原因,但根据最佳实践,将配置对象作为参数传递给功能类(如 ModelTrainer)的构造函数是一种常见的依赖注入模式,可以提高代码的模块化和可测试性。

原始 ModelTrainer 类的 __init__ 方法:

class ModelTrainer:
    def __init__(self):
        # 这里硬编码实例化了 ModelTrainerConfig,而不是接收外部传入的配置
        self.model_trainer_config = ModelTrainerConfig()
登录后复制

这种方式使得 ModelTrainer 类与 ModelTrainerConfig 的实例化紧密耦合。更好的做法是将 ModelTrainerConfig 对象作为参数传入。

uBrand Logo生成器
uBrand Logo生成器

uBrand Logo生成器是一款强大的AI智能LOGO设计工具。

uBrand Logo生成器 124
查看详情 uBrand Logo生成器

方法 A: 使用位置参数传递配置

  1. 修改 ModelTrainer 类的 __init__ 方法:

    import os
    import sys
    import joblib # 假设 joblib 已经被导入用于保存模型
    
    # ... 其他导入 ...
    
    # 确保 ModelTrainerConfig 已经按照解决方案一进行了修正
    # from your_project_path.config.configuration import ModelTrainerConfig # 假设路径
    
    class ModelTrainer:
        # 接受一个 ModelTrainerConfig 实例作为位置参数
        def __init__(self, model_trainer_config: ModelTrainerConfig):
            self.model_trainer_config = model_trainer_config
    
        # ... 其他方法 (save_obj, evaluate_model, initiate_model_training) ...
    
        # 示例:修正后的 save_obj 方法,确保其为实例方法或静态方法
        def save_obj(self, 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:
                # logging.info('Error occured in utils save_obj') # 确保 logger 可用
                raise e
    
        # 示例:修正后的 evaluate_model 方法,确保其为实例方法或静态方法
        @staticmethod # 标记为静态方法,因为它不依赖实例状态
        def evaluate_model(X_train, y_train, X_test, y_test, models):
            # ... 原 evaluate_model 逻辑 ...
            pass # 实际代码保持不变
    
        def initiate_model_training(self, X_train, X_test, y_train, y_test):
            # ... 原 initiate_model_training 逻辑 ...
            # 调用 save_obj 时,需要通过 self.save_obj
            self.save_obj(
                file_path=self.model_trainer_config.trained_model_file_path,
                obj=best_model
            )
            # ...
    登录后复制
  2. 修改 ModelTrainer 类的实例化方式:

    from your_project_path.config.configuration import ConfigurationManager
    # from your_project_path.components.model_trainer import ModelTrainer # 假设路径
    
    try:
        config_manager = ConfigurationManager()
        # 首先获取 ModelTrainerConfig 实例
        model_trainer_config_instance = config_manager.get_model_trainer_config()
    
        # 将 ModelTrainerConfig 实例作为位置参数传入 ModelTrainer 构造函数
        model_trainer = ModelTrainer(model_trainer_config_instance)
        model_trainer.initiate_model_training(X_train, X_test, y_train, y_test) # 假设 X_train, etc. 已定义
    except Exception as e:
        raise e
    登录后复制

方法 B: 使用关键字参数传递配置

  1. 修改 ModelTrainer 类的 __init__ 方法:

    class ModelTrainer:
        # 接受一个 ModelTrainerConfig 实例作为关键字参数 'config'
        def __init__(self, config: ModelTrainerConfig):
            self.model_trainer_config = config # 将传入的 config 赋值给内部属性
    
        # ... 其他方法 (同上) ...
    登录后复制
  2. 修改 ModelTrainer 类的实例化方式:

    from your_project_path.config.configuration import ConfigurationManager
    # from your_project_path.components.model_trainer import ModelTrainer # 假设路径
    
    try:
        config_manager = ConfigurationManager()
        # 首先获取 ModelTrainerConfig 实例
        model_trainer_config_instance = config_manager.get_model_trainer_config()
    
        # 将 ModelTrainerConfig 实例作为关键字参数 'config' 传入 ModelTrainer 构造函数
        model_trainer = ModelTrainer(config=model_trainer_config_instance)
        model_trainer.initiate_model_training(X_train, X_test, y_train, y_test) # 假设 X_train, etc. 已定义
    except Exception as e:
        raise e
    登录后复制

综合代码示例

结合上述两种修正,一个更完整和健壮的 ModelTrainer 实例化流程应如下:

1. ModelTrainerConfig 定义 (例如在 src/config/configuration.py 或 entity 文件夹中):

# src/entity/config_entity.py 或类似路径
import os
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class DataIngestionConfig:
    root_dir: Path
    source_URL: str
    local_data_file: Path
    unzip_dir: Path

@dataclass(frozen=True)
class DataValidationConfig:
    root_dir: Path
    STATUS_FILE: Path
    unzip_data_dir: Path
    all_schema: dict

@dataclass(frozen=True)
class DataTransformationConfig:
    root_dir: Path
    data_path: Path
    processor_name: str
    target_column: str

@dataclass(frozen=True)
class ModelTrainerConfig:
    root_dir: Path
    train_data_path: Path
    test_data_path: Path
    trained_model_file_path: Path # 确保此参数已定义
    model_name: str
    alpha: float
    l1_ratio: float
    target_column: str

# ... 其他配置类 ...
登录后复制

2. ModelTrainer 类定义 (例如在 src/components/model_trainer.py):

# src/components/model_trainer.py
import os
import sys
import pandas as pd
import numpy as np
import joblib # 用于保存模型

from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import r2_score

# 假设 logging 模块已配置
# from your_project_path.logger import logging
# 假设 ModelTrainerConfig 已从 entity 导入
from your_project_path.entity.config_entity import ModelTrainerConfig

class ModelTrainer:
    def __init__(self, config: ModelTrainerConfig): # 接受配置对象
        self.config = config # 将传入的配置赋值给实例属性

    # 将 save_obj 和 evaluate_model 改为静态方法或辅助函数,或确保它们正确使用 self
    @staticmethod
    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:
            # logging.error('Error occurred in utils save_obj', exc_info=True)
            raise e

    @staticmethod
    def evaluate_model(X_train, y_train, X_test, y_test, models):
        try:
            report = {}
            for name, model in models.items():
                model.fit(X_train, y_train)
                y_test_pred = model.predict(X_test)
                test_model_score = r2_score(y_test, y_test_pred)
                report[name] = test_model_score
            return report
        except Exception as e:
            # logging.error('Exception occurred during model evaluation', exc_info=True)
            raise e

    def initiate_model_training(self, X_train, X_test, y_train, y_test):
        # logging.info('Initiating model training...')
        try:
            models = {
                'LinearRegression': LinearRegression(),
                'Lasso': Lasso(alpha=self.config.alpha), # 使用配置中的参数
                'Ridge': Ridge(alpha=self.config.alpha),
                'Elasticnet': ElasticNet(alpha=self.config.alpha, l1_ratio=self.config.l1_ratio),
                'RandomForestRegressor': RandomForestRegressor(),
                'GradientBoostRegressor': GradientBoostingRegressor(),
                "AdaBoost": AdaBoostRegressor(),
                'DecisionTreeRegressor': DecisionTreeRegressor(),
                "SupportVectorRegressor": SVR(),
                "KNN": KNeighborsRegressor()
            }

            model_report: dict = self.evaluate_model(X_train, y_train, X_test, y_test, models)
            print(f"Model Report: {model_report}")
            # logging.info(f'Model Report : {model_report}')

            best_model_score = max(sorted(model_report.values()))
            best_model_name = [name for name, score in model_report.items() if score == best_model_score][0]
            best_model = models[best_model_name]

            print(f"Best Model Found, Model Name: {best_model_name}, R2-score: {best_model_score}")
            # logging.info(f"Best Model Found, Model name: {best_model_name}, R2-score: {best_model_score}")

            self.save_obj(
                file_path=self.config.trained_model_file_path, # 从 self.config 获取路径
                obj=best_model
            )
            # logging.info(f"Best model saved to {self.config.trained_model_file_path}")

        except Exception as e:
            # logging.error('Exception occurred at model training', exc_info=True)
            raise e
登录后复制

3. 运行脚本 (例如在 research/04_model_trainer.ipynb 或 main.py):

# research/04_model_trainer.ipynb 或 main.py
from your_project_path.config.configuration import ConfigurationManager
from your_project_path.components.model_trainer import ModelTrainer
# 假设 X_train, X_test, y_train, y_test 已经从之前的数据处理阶段加载或生成

try:
    config
登录后复制

以上就是ML项目模型训练器TypeError:构造函数参数不匹配问题诊断与解决的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号