You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python字符串形式的ExtraTreesClassifier转为sklearn分类器对象?

Convert String-formatted ExtraTreesClassifier Config to Usable Sklearn Object

Got a string representation of an ExtraTreesClassifier configuration and need to turn it into an actual sklearn classifier instance? Here's a concise, reliable approach:

Working Code Snippet

import ast
from sklearn.ensemble import ExtraTreesClassifier

# Your input configuration string
config_str = "ExtraTreesClassifier(bootstrap=False, class_weight=None, max_depth=None, max_features=11, min_samples_leaf=2, min_samples_split=8, n_estimators=20, criterion=\"gini\", n_jobs=4, random_state=12)"

# Convert the string to a functional classifier object
classifier = ExtraTreesClassifier(**ast.literal_eval("{" + config_str.split("(", 1)[1][:-1].replace("=", ":") + "}"))

# Verify the result type
print(type(classifier))  # Output: <class 'sklearn.ensemble._forest.ExtraTreesClassifier'>

Step-by-Step Breakdown

Let’s unpack how this works:

  • Strip the classifier wrapper: config_str.split("(", 1)[1][:-1] removes the leading ExtraTreesClassifier( and trailing ) from the input string, leaving only the comma-separated parameter key-value pairs.
  • Adjust to dictionary syntax: .replace("=", ":") swaps equals signs with colons to convert the parameter string into valid Python dictionary syntax, then wrapping it in {} creates a complete dictionary string.
  • Parse and initialize the classifier: ast.literal_eval() safely parses the dictionary string into an actual Python dictionary, and the ** operator unpacks this dictionary as keyword arguments to initialize the ExtraTreesClassifier instance.

内容的提问来源于stack exchange,提问作者doyz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:02:19