scikit-learn CART String Data

machine-learning, python, scikit-learn

Solution

You need to transform string-valued features to numeric ones in a NumPy array; `DictVectorizer` does that for you.

samples = [['asdf', '1'], ['asdf', '0']]
# turn the samples into dicts
samples = [dict(enumerate(sample)) for sample in samples]

# turn list of dicts into a numpy array
vect = DictVectorizer(sparse=False)
X = vect.fit_transform(samples)

clf = DecisionTreeClassifier()
clf.fit(X, ['2', '3'])

Remember to use `vect.transform` on the test samples, after converting those to dicts.

Problem

Are you able to train a DecisionTreeClassifier with string data? When I try to use String data I get a ValueError: could not converter string to float `clf = DecisionTreeClassifier() clf.fit([['asdf', '1'], ['asdf', '0']], ['2', '3'])`

Original source