1

I am try DecisionTreeClassifier with parameters in a string.

 print d    # d= 'max_depth=100'
 clf = DecisionTreeClassifier(d)
 clf.fit(X[:3000,], labels[:3000])

I am getting below error for this case. If I use clf = DecisionTreeClassifier(max_depth=100) it works fine.

Traceback (most recent call last):
  File "train.py", line 120, in <module>
    grid_search_generalized(X, labels, {"max_depth":[i for i in range(100, 200)]})
  File "train.py", line 51, in grid_search_generalized
    clf.fit(X[:3000,], labels[:3000])
  File "/usr/local/lib/python2.7/dist-packages/sklearn/tree/tree.py", line 790, in fit
    X_idx_sorted=X_idx_sorted)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/tree/tree.py", line 326, in fit
    criterion = CRITERIA_CLF[self.criterion](self.n_outputs_,
KeyError: 'max_depth=100'
tarun14110
  • 940
  • 5
  • 26
  • 57

2 Answers2

1

You are passing the argument as a string object and not as an optional parameter.
If you really have to call the constructor with this string, you can use this code:

 arg = dict([d.split("=")])
 clf = DecisionTreeClassifier(**arg)

You can read more about arguments unpacking in this link
Passing a dictionary to a function in python as keyword parameters

Guy Goldenberg
  • 809
  • 7
  • 20
  • `Traceback (most recent call last): File "train.py", line 121, in grid_search_generalized(X, labels, {"max_depth":[100]}) File "train.py", line 52, in grid_search_generalized clf.fit(X[:3000,], labels[:3000]) File "/usr/local/lib/python2.7/dist-packages/sklearn/tree/tree.py", line 790, in fit X_idx_sorted=X_idx_sorted) File "/usr/local/lib/python2.7/dist-packages/sklearn/tree/tree.py", line 326, in fit criterion = CRITERIA_CLF[self.criterion](self.n_outputs_, TypeError: unhashable type: 'dict'` Getting this error now. – tarun14110 Aug 27 '17 at 05:02
1

keyworded variable arguments hasn't been defined in DecisionTreeClassifier function. max_depth can be passed as a keyword argument.Please try this code:

d= 'max_depth=100'
arg = dict([d.split("=")])
i = int(next(iter(arg.values())))
k = next(iter(arg.keys()))
clf = DecisionTreeClassifier(max_depth=args['max_depth'])
clf.fit(X[:3000,], labels[:3000])

Output:

DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=100,
                       max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=1, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort=False,
                       random_state=None, splitter='best')