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

灵枢SparkVertex
灵枢SparkVertex

零代码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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
堆和栈的区别
堆和栈的区别

堆和栈的区别:1、内存分配方式不同;2、大小不同;3、数据访问方式不同;4、数据的生命周期。本专题为大家提供堆和栈的区别的相关的文章、下载、课程内容,供大家免费下载体验。

448

2023.07.18

堆和栈区别
堆和栈区别

堆(Heap)和栈(Stack)是计算机中两种常见的内存分配机制。它们在内存管理的方式、分配方式以及使用场景上有很大的区别。本文将详细介绍堆和栈的特点、区别以及各自的使用场景。php中文网给大家带来了相关的教程以及文章欢迎大家前来学习阅读。

606

2023.08.10

堆和栈的区别
堆和栈的区别

堆和栈的区别:1、内存分配方式不同;2、大小不同;3、数据访问方式不同;4、数据的生命周期。本专题为大家提供堆和栈的区别的相关的文章、下载、课程内容,供大家免费下载体验。

448

2023.07.18

堆和栈区别
堆和栈区别

堆(Heap)和栈(Stack)是计算机中两种常见的内存分配机制。它们在内存管理的方式、分配方式以及使用场景上有很大的区别。本文将详细介绍堆和栈的特点、区别以及各自的使用场景。php中文网给大家带来了相关的教程以及文章欢迎大家前来学习阅读。

606

2023.08.10

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

76

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

116

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

347

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

63

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

109

2026.03.09

热门下载

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

精品课程

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

共4课时 | 22.5万人学习

Django 教程
Django 教程

共28课时 | 5万人学习

SciPy 教程
SciPy 教程

共10课时 | 2万人学习

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

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