如何在Python中动态构建模型?

发布于 2025-01-23 11:24:09 字数 524 浏览 3 评论 0原文

我有一个带有Alogitthm和超级参数的列的数据框,均以字符串格式,

看起来像这样。

id   Alg
------------
1    RandomForestClassifier(max_depth=2, random_state=0)
2    LinearRegression(n_jobs=-1)
3    RandomForestClassifier(n_estimators=750)
4    ExtraTreesClassifier(criterion='entropy')

有什么方法可以动态运行该算法?

所以我的代码将是这样的

for strCode in df["Alg"]:
   model = SomeFunction(strCode) # <---------------- strCode should run dynamically so model can be generated
   model.fit(X_train, y_train)

I have a dataframe that has a column with an alogitthm and hyperparameters all in string format

it looks like this.

id   Alg
------------
1    RandomForestClassifier(max_depth=2, random_state=0)
2    LinearRegression(n_jobs=-1)
3    RandomForestClassifier(n_estimators=750)
4    ExtraTreesClassifier(criterion='entropy')

is there a way I can run the algorithm dynamically?

so my code will be something like this

for strCode in df["Alg"]:
   model = SomeFunction(strCode) # <---------------- strCode should run dynamically so model can be generated
   model.fit(X_train, y_train)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱倦旧时光 2025-01-30 11:24:09

您可能正在寻找 evary() 函数将传递的字符串评估为python表达式。

from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier  # noqa
from sklearn.linear_model import LinearRegression  # noqa

algos = [
    "RandomForestClassifier(max_depth=2, random_state=0)",
    "LinearRegression(n_jobs=-1)",
    "RandomForestClassifier(n_estimators=750)",
    "ExtraTreesClassifier(criterion='entropy')",
]
for strCode in algos:
    model = eval(strCode)  # eval basically executes whatever string it gets
    model.fit(X_train, y_train)

You might be looking for the eval() function which evaluates the passed string as a python expression.

from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier  # noqa
from sklearn.linear_model import LinearRegression  # noqa

algos = [
    "RandomForestClassifier(max_depth=2, random_state=0)",
    "LinearRegression(n_jobs=-1)",
    "RandomForestClassifier(n_estimators=750)",
    "ExtraTreesClassifier(criterion='entropy')",
]
for strCode in algos:
    model = eval(strCode)  # eval basically executes whatever string it gets
    model.fit(X_train, y_train)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文