Неразборчивый тип "ломтик" при попытке построить Случайный Лес - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь построить свой Случайный Лес, но он выдает мне следующую ошибку: Ошибка типа: unhashable type: 'slice' в дополнение к отображению пустых графиков. Сама модель работает нормально, давая мне приемлемую точность и отзывные баллы.

from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=500, random_state=0) 
forest.fit(train_x, train_y) 

import matplotlib as plt
import matplotlib.pyplot as plt
import mglearn

fig, axes = plt.subplots(2, 3, figsize=(20, 10))
for i, (ax, tree) in enumerate(zip(axes.ravel(), forest.estimators_)):
    ax.set_title("Tree {}".format(i))
    mglearn.plots.plot_tree_partition(train_x, train_y, tree, ax=ax)

mglearn.plots.plot_2d_separator(forest, train_x, fill=True, ax=axes[-1, -1],
                                alpha=.4)
axes[-1, -1].set_title("Random Forest")
mglearn.discrete_scatter(train_x[:, 0], train_x[:, 1], train_y)

См. Подробную ошибку ниже:

TypeError                                 Traceback (most recent call last)
<ipython-input-67-26f28abf17a0> in <module>()
      2 for i, (ax, tree) in enumerate(zip(axes.ravel(), forest.estimators_)):
      3     ax.set_title("Tree {}".format(i))
----> 4     mglearn.plots.plot_tree_partition(train_x, train_y, tree, ax=ax)
      5 
      6 mglearn.plots.plot_2d_separator(forest, train_x, fill=True, ax=axes[-1, -1],

~\AppData\Local\Continuum\anaconda3\lib\site-packages\mglearn\plot_interactive_tree.py in plot_tree_partition(X, y, tree, ax)
     65     eps = X.std() / 2.
     66 
---> 67     x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
     68     y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
     69     xx = np.linspace(x_min, x_max, 1000)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2137             return self._getitem_multilevel(key)
   2138         else:
-> 2139             return self._getitem_column(key)
   2140 
   2141     def _getitem_column(self, key):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
   2144         # get column
   2145         if self.columns.is_unique:
-> 2146             return self._get_item_cache(key)
   2147 
   2148         # duplicate columns & possible reduce dimensionality

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   1838         """Return the cached item, item represents a label indexer."""
   1839         cache = self._item_cache
-> 1840         res = cache.get(item)
   1841         if res is None:
   1842             values = self._data.get(item)

TypeError: unhashable type: 'slice'

train_x

train_y

1 Ответ

0 голосов
/ 02 мая 2018

Ошибка исходит от панды, потому что функция не поддерживает ее

Попробуйте заменить ваш фрейм данных train_x на train_x.values в вашем plot_2d_separator

Надеюсь, это поможет,
Приветствия

...