python - Python - 通过传递带有模型名称的字符串作为输入来获取 Scikit-Learn 分类器
问题描述
我想通过将带有模型名称的字符串作为输入传递来检索特定的 SKLearn 模型对象。例如,目前我有这个来加载 MultinomialNB 模型
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB(alpha=1.0,
class_prior=None,
fit_prior=True)
我想要一种方法:
def get_model(model_name):
(...)
return model
这样当我执行 get_model("MultinomialNB") 时,我会得到与nb
上面代码相同的对象。为此在 Scikit-Learn 中实现了什么?
解决方案
One option is to use importlib
. It will force you to also pass the module from which to import, though. With this approach, model hyperparameters should also be parametrized in the function call.
Example:
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
which then you could call by doing e.g.
model_params = {"alpha": 1.0, "class_prior": None, "fit_prior": True}
nb = get_model("MultinomialNB", "sklearn.naive_bayes", model_params)
推荐阅读
- php - 未捕获的异常。使用 sql server 和基本映像 php:7.3-apache 在 docker 容器中找不到驱动程序
- mysql - 加入日历表并过滤某些用户时显示缺失的日期
- reactjs - 如何使用单个 useState 在 reactjs 中创建多个下拉列表
- python - 发送带有套接字的图像时出现“std::out_of_range”错误
- c# - 如何在 Visual Studio 中执行自定义活动
- sql - 如何将表中的行聚合到一个字符串?
- azure - 如何通过代码编辑 Azure Health Bot 的文件?
- javascript - 子组件渲染时触发父组件的重新渲染
- angular - 无法读取未定义的属性(读取 emod)
- entity-framework-core - 更新到 .NET 5 DataAnnotations.Schema 不再起作用。LINQ 连接多个数据库/查询失败