尝试绘制随机森林时不可用的类型“切片”

时间:2018-05-02 11:52:40

标签: python pandas matplotlib scikit-learn random-forest

我正在尝试绘制我的随机森林,但它给了我以下错误:TypeError:不可用类型:'sl​​ice'除了显示空图。该模型本身工作正常,给我可接受的精度和召回分数。

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 :(得分:0)

错误来自大熊猫,因为该功能并不支持它

尝试使用train_x

中的train_x.values替换您的数据框plot_2d_separator

希望这有帮助,
干杯