【问题标题】:How to properly define class for a random forest model?如何正确定义随机森林模型的类?
【发布时间】:2022-07-29 17:34:31
【问题描述】:

我正在使用我训练并保存的随机森林。我想创建一个使用该模型并提供预测的类。 我是新来的课程,我做了如下:

from sklearn.ensemble import RandomForestClassifier
import os
import joblib

model_path = r"the path of the model"
model =  joblib.load(os.path.join(model_path,'rf.pkl'))

class MODEL_RF(RandomForestClassifier):

 def load_model(self):
        self.model = model

 def get_pred(self, df):
        validation_features = np.array(df)
        self.model = self.load_model()
        pred = self.predict(validation_features)
        predict_prob = self.predict_proba(validation_features)
        return pred,predict_prob

model_m = MODEL_RF()
prediction, probs = model_m.get_pred(input_df)

然而, 我收到如下错误:

    raise NotFittedError(msg % {"name": type(estimator).__name__})
sklearn.exceptions.NotFittedError: This MODEL_RF instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

【问题讨论】:

  • 始终提供完整的错误回溯;它包含有价值的调试信息。

标签: python class scikit-learn random-forest production


【解决方案1】:

出现错误是因为您的类继承自RandomForestClassifier,因此self.predict 行试图调用sklearn 定义的predict 方法,但您的包装类不包含任何有关随机森林的拟合信息;所有这些都包含在 属性 self.model,但不能直接用作您的类的属性。

我不相信有理由创建一个新类只是为了包装一个腌制的 sklearn 模型。只需将get_pred 中的代码直接放入脚本中即可。如果您确实有充分的理由,那么我建议您跳过从RandomForestClassifier 继承,而是始终调用self.model.predictself.model.predict_proba 等。

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2017-10-23
    • 1970-01-01
    • 2019-05-07
    • 2019-07-10
    • 2017-08-11
    • 2019-12-07
    • 2016-04-09
    • 2020-02-25
    相关资源
    最近更新 更多