【发布时间】:2015-11-10 15:21:23
【问题描述】:
我正在尝试构建一个名为 SafeModel 的工厂类,其 generate 方法接受一个 scikit-learn 类的实例,更改它的一些属性,并返回相同的实例.具体来说,对于这个例子,我想访问返回模型的 coef_ 属性,在案例 1)如果基础 scikit-learn 类包含 coef_,则返回该类'coef_,在案例 1 中2) 如果底层 scikit-learn 类包含feature_importances_,则返回该类'feature_importances。
我已经成功地为 Python 类的实例修补了属性。我对 Python 类实例的猴子修补魔术方法的成功率较低。我的情况需要注意的是:属性coef_ 和feature_importances 从未在 scikit-learn 类实例化时定义;相反,它们仅在对各自的类调用 fit 方法后定义。因此,我无法覆盖属性定义本身。
from types import MethodType
class SafeModel:
FALLBACK_ATTRIBUTES = {
'coef_': ['feature_importances_'],
}
@classmethod
def generate(cls, model):
safe_model = cls._secure_attributes(model)
return safe_model
@classmethod
def _secure_attributes(cls, model):
def __secure_getattr__(self, name):
for fallback_attribute in cls.FALLBACK_ATTRIBUTES[name]:
try:
return getattr(self, fallback_attribute)
except:
continue
model.__getattr__ = MethodType(__secure_getattr__, model)
return model
from sklearn.ensemble import RandomForestClassifier
model = SafeModel.generate(RandomForestClassifier())
model.coef_ # AttributeError: 'RandomForestClassifier' object has no attribute 'coef_'
【问题讨论】:
标签: python scikit-learn monkeypatching magic-methods