测试 sklearn 模型是否已安装的最佳方法是什么? [英] What's the best way to test whether an sklearn model has been fitted?

查看:27
本文介绍了测试 sklearn 模型是否已安装的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查 sklearn 模型是否已拟合的最优雅的方法是什么?即它的 fit() 函数在实例化后是否被调用.

What's the most elegant way to check whether an sklearn model has been fitted? i.e. whether its fit() function has been called after it was instantiated, or not.

推荐答案

您可以执行以下操作:

from sklearn.exceptions import NotFittedError

for model in models:
    try:
        model.predict(some_test_data)
    except NotFittedError as e:
        print(repr(e))

理想情况下,您应该根据预期结果检查 model.predict 的结果,但如果您只想知道模型是否拟合就足够了.

Ideally you would check the results of model.predict against expected results but if all you want to know if wether the model is fitted or not that should suffice.

一些评论者建议使用 check_is_fitted.我认为 check_is_fitted 是一种内部方法.大多数算法会在它们的 predict 方法中调用 check_is_fitted,如果需要,这反过来可能会引发 NotFittedError.直接使用 check_is_fitted 的问题在于它是特定于模型的,即您需要根据您的算法知道要检查哪些成员.例如:

Some commenters have suggested using check_is_fitted. I consider check_is_fitted an internal method. Most algorithms will call check_is_fitted inside their predict method which in turn might raise NotFittedError if needed. The problem with using check_is_fitted directly is that it is model specific, i.e. you need to know which members to check depending on your algorithm. For example:

╔════════════════╦════════════════════════════════════════════╗
║ Tree models    ║ check_is_fitted(self, 'tree_')             ║
║ Linear models  ║ check_is_fitted(self, 'coefs_')            ║
║ KMeans         ║ check_is_fitted(self, 'cluster_centers_')  ║
║ SVM            ║ check_is_fitted(self, 'support_')          ║
╚════════════════╩════════════════════════════════════════════╝

等等.所以总的来说,我建议调用 model.predict() 并让特定算法处理检查它是否已经安装的最佳方法.

and so on. So in general I would recommend calling model.predict() and letting the specific algorithm handle the best way to check whether it is already fitted or not.

这篇关于测试 sklearn 模型是否已安装的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆