3

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

doyz
  • 887
  • 2
  • 18
  • 43
  • Use `eval` althought it's not recommended – sshashank124 May 16 '18 at 14:10
  • that string is the call for instantiating the `ExtraTreesClassifier` object. do `my_classifier =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) ` – Mohammad Athar May 16 '18 at 14:13
  • @sshashank124oh i have tried that before.. but will face this error: SyntaxError: keyword can't be an expression – doyz May 16 '18 at 14:14
  • Possible duplicate of [Convert string to Python class object?](https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object) – Bram Vanroy May 16 '18 at 14:21
  • 1
    Post the solution as an answer and accept it – Vivek Kumar May 17 '18 at 04:49

0 Answers0