如何将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 leadingExtraTreesClassifier(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 theExtraTreesClassifierinstance.
内容的提问来源于stack exchange,提问作者doyz
相关产品推荐
相关产品推荐

