Итак, вам нужно закодировать ваши строковые данные в числовые c функции. Здесь я копирую ваш ввод:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
from sklearn.tree import DecisionTreeClassifier
df = pd.read_clipboard(header=None, sep=',')
0 1 2 3
0 cucumber green 15 4
1 tomato red 7 7
2 carrots Orange 13 3
3 onion White 8 8
4 potatoes Gray 8 6
5 apple Red 7 6
6 apple Yellow 6 5
Вам нужно будет закодировать столбец "color":
ohe = OneHotEncoder(sparse=False)
colors = ohe.fit_transform(df.iloc[:, 1].values.reshape(-1, 1))
Теперь это выглядит так, каждый цвет столбец:
array([[0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], ...
Затем вам нужно объединить его с другими столбцами, которые уже нумеруются c:
inputs = np.concatenate([df.iloc[:, 2:].values, colors], axis=1)
Теперь вам нужно повернуть свои цели (плод ) в числа:
oe = OrdinalEncoder()
targets = oe.fit_transform(df.iloc[:, 0].values.reshape(-1, 1))
Теперь они выглядят так:
array([[ 5.],
[10.],
[ 2.],
[ 7.],
[ 9.],
[ 0.], ...
Затем вы можете уместить свое дерево решений:
clf = DecisionTreeClassifier()
clf = clf.fit(inputs, targets)
И теперь вы может даже предсказать новые данные:
new_data = [["red", 7, 7], ["Yellow", 5, 6]]
new_data = np.concatenate([[i[1:] for i in new_data],
ohe.transform([[i[0]] for i in new_data])], axis=1)
answer = clf.predict(new_data)
oe.categories_[0][answer.astype(int)]
Out[88]: array(['tomato', 'apple'], dtype=object)