0

0

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

花韻仙語

花韻仙語

发布时间:2025-09-22 14:44:38

|

1180人浏览过

|

来源于php中文网

原创

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 对象作为参数传入。

腾讯AI 开放平台
腾讯AI 开放平台

腾讯AI开放平台

下载

方法 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

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

748

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

634

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

758

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

617

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1261

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

577

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

705

2023.08.11

Java 项目构建与依赖管理(Maven / Gradle)
Java 项目构建与依赖管理(Maven / Gradle)

本专题系统讲解 Java 项目构建与依赖管理的完整体系,重点覆盖 Maven 与 Gradle 的核心概念、项目生命周期、依赖冲突解决、多模块项目管理、构建加速与版本发布规范。通过真实项目结构示例,帮助学习者掌握 从零搭建、维护到发布 Java 工程的标准化流程,提升在实际团队开发中的工程能力与协作效率。

10

2026.01.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 3万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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