If i have a string:
"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)"
What is the best way to convert it to an sklearn classifier so that i can fit my dataset to it?
Desired output:
<class 'sklearn.ensemble.forest.ExtraTreesClassifier'>
EDIT
In my case, the string is not wrapped in hyphens (understand that without the hypens i will be able to call the sklearn function), rather the variable is of type string.
SOLUTION
I have managed to solve it by first extracting the parameters to dictionary form, then placing it within the sklearn estimator:
import ast
ExtraTreesClassifier(**ast.literal_eval("{"+i.split("(", 1)[1][:-1].replace("=",":")+"}"))
i.split("(", 1)[1][:-1]
removes "ExtraTreesClassifier("
and ")"
from the string.
To format string to the same syntax as a dictionary, use:
.replace("=",":")
then wrap brackets "{"
Because this is still a string representation of a dictionary, to pass it as parameters to the sklearn estimator, this is needed to be wrapped around the dictionary:
**ast.literal_eval()
-> see this link