【问题标题】:How to fit a list or a dictionary of models in python?如何在 python 中拟合模型列表或字典?
【发布时间】:2021-04-20 22:46:32
【问题描述】:

我有一些模型,我正在尝试将它们全部拟合。

目前我已经尝试过使用字典并适合它们:

dictionary_of_models = {'catboost':CatBoostClassifier(random_state=0,), 'logistic_regression':LogisticRegression(random_state=0)}
for model in dictionary_of_models.keys():
            print(model)
            dictionary_of_models[model]=model.fit(X_train, y_train)

但是,即使模型被打印出来,我也会收到这个错误:

model.fit(X_train, y_train)
AttributeError: 'str' object has no attribute 'fit'

代码有什么问题?

我认为字符串将传递给 fit 函数而不是模型对象,但我不知道我可以从字典创建模型,除非我尝试过。

【问题讨论】:

    标签: python python-3.x dictionary machine-learning scikit-learn


    【解决方案1】:

    问题是您尝试将fit 应用于您为模型提供的名称。你必须适合 model 而不是它的名字。

    dictionary_of_models = {'catboost':CatBoostClassifier(random_state=0,), 
                            'logistic_regression':LogisticRegression(random_state=0)}
    for name, model in dictionary_of_models.items():
            print(name)
            dictionary_of_models[model]=model.fit(X_train, y_train)
    

    【讨论】:

      【解决方案2】:

      补充 Prune 的回答,我相信你可以避免itemsdictionary_of_model[model] 会生成一个 KeyError ,因为你没有传递字典的键,而是值本身。

      请尝试:

      for model in dictionary_of_models:
              print(model)
              dictionary_of_models[model] = dictionary_of_models[model].fit(X_train, y_train)
      

      【讨论】:

      • 嗨,我试过了,上面的属性错误没有了,但现在我有一个关键错误:'catboost',分段错误(已创建转储)
      • 再次运行,没有核心转储,只有 Key Error:'catboost'
      • 使用“dictionary_of models.items()”再次运行并得到“TypeError: unhashable type: 'CatBoostClassifier'”
      猜你喜欢
      • 2016-11-12
      • 2021-04-13
      • 2018-10-22
      • 2018-05-28
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多