Python—通过将带有模型名的字符串作为输入来获取Scikit学习分类器
我想通过传递一个带有模型名称的字符串作为输入来检索特定的SKLearn模型对象。例如,目前我要加载一个多项式NB模型Python—通过将带有模型名的字符串作为输入来获取Scikit学习分类器,python,scikit-learn,Python,Scikit Learn,我想通过传递一个带有模型名称的字符串作为输入来检索特定的SKLearn模型对象。例如,目前我要加载一个多项式NB模型 from sklearn.naive_bayes import MultinomialNB nb = MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) 我希望有一种方法,以便: def get_model(model_name):
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB(alpha=1.0,
class_prior=None,
fit_prior=True)
我希望有一种方法,以便:
def get_model(model_name):
(...)
return model
因此,当我得到_模型(“多项式nb”)时,我得到与上面代码的
nb
相同的对象。Scikit中实现的任何东西都可以用于此学习?一个选项是使用importlib
。不过,这将迫使您同时传递要从中导入的模块。使用这种方法,模型超参数也应该在函数调用中参数化
例如:
import importlib
import sklearn
def get_model(
model_name: str, import_module: str, model_params: dict
) -> sklearn.base.BaseEstimator:
"""Returns a scikit-learn model."""
model_class = getattr(importlib.import_module(import_module), model_name)
model = model_class(**model_params) # Instantiates the model
return model
然后你可以通过这样做来调用它
model_params = {"alpha": 1.0, "class_prior": None, "fit_prior": True}
nb = get_model("MultinomialNB", "sklearn.naive_bayes", model_params)
您可以创建一个字典,其中键是名称,值是模型<代码>例如{“多项式nb”:“多项式nb(alpha=1.0,class_prior=None,fit_prior=True)”,“”:“model method”}@Vishal好主意,谢谢!