我已经测试了几种回归者从科学-学习。但是,当我只对回归者使用if-语句时,我会遇到错误情况,如下面的示例代码。
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import GradientBoostingRegressor, HistGradientBoostingRegressor
for j, model in enumerate([MLPRegressor(), HistGradientBoostingRegressor(), GradientBoostingRegressor()]):
if model:
print(f'{j}: True. You defined the model: %s'%type(model))0: True. You defined the model: <class 'sklearn.neural_network._multilayer_perceptron.MLPRegressor'>
1: True. You defined the model: <class 'sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor'>
AttributeError: 'GradientBoostingRegressor' object has no attribute 'estimators_'与前两个模型不同,只有第三个模型会导致AttributeError。另一方面,if model is not None:不会导致错误。为什么会这样呢?
发布于 2022-09-07 13:19:55
在计算if not <object>时,python解释器检查__nonzero__() dunder (如果实现的话),然后检查__len__()的非零返回值(如果实现的话),最后将对象与None进行比较。
根据继承的不同,在不同的sklearn模型类中,__len__()实现存在一些不一致之处。这是一个已知的问题(例如,https://github.com/scikit-learn/scikit-learn/issues/23769、https://github.com/scikit-learn/scikit-learn/issues/10487),但据我所知,它没有在短期内得到纠正的优先次序。
使用if <object> is (not) None是一种推荐的解决方法。
https://stackoverflow.com/questions/73635730
复制相似问题