Как исправить ключевую ошибку при создании графиков? - PullRequest
0 голосов
/ 12 апреля 2019

Я сравниваю несколько классификаторов в своем собственном наборе данных.Во время построения я получаю сообщение об ошибке:

KeyError Traceback (последний вызов был последним) ~ \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ colors.py в to_rgba (c, alpha) 173 try: -> 174 rgba = _colors_full_map.cache [c, alpha] 175 за исключением (KeyError, TypeError): # Не в кеше или не подлежит восстановлению.

KeyError: ('myLabel', None)

Во время обработки вышеуказанного исключения произошло другое исключение:

ValueError Traceback (последний вызов был последним) ~ \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \axes_axes.py в scatter (self, x, y, s, c, маркер, cmap, норма, vmin, vmax, alpha, linewidths, verts, edgecolors, ** kwargs) 4231 try: # Тогда «c» приемлемо как PathCollectionfacecolors?-> 4232 colors = mcolors.to_rgba_array (c) 4233 n_elem = colors.shape [0]

~ \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ colors.py в to_rgba_array (c, alpha) 274 для i, cc в перечислении (c): -> 275 результат [i] = to_rgba (cc, alpha) 276 возвращаемый результат

~ \ AppData \ Local \ Continuum \ anaconda3 \ lib\ site-packages \ matplotlib \ colors.py в to_rgba (c, alpha) 175 за исключением (KeyError, TypeError): # Не в кеше или недоступно для хранения.-> 176 rgba = _to_rgba_no_colorcycle (c, alpha) 177 try:

~ \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ colors.py в _to_rgba_no_colorcycle (c, alpha) 219pass -> 220 повышение ValueError («Неверный аргумент RGBA: {! r}». format (orig_c)) 221 # цвет кортежа.

ValueError: Неверный аргумент RGBA: «myLabel»

Во время обработки вышеупомянутого исключения произошло другое исключение:

ValueError Traceback (последний последний вызов) в 21 # Построить тренировочные точки 22 ax.scatter (X_train [:, 0], X_train [:, 1], c = y_train.ravel (), cmap = cm_bright, ---> 23 edgecolors = 'k') 24 25

~ \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib__init__.py in inner (ax, data, * args, ** kwargs) 1808
"список Matplotlib!)"% (label_namer, func. name ), 1809
RuntimeWarning, stacklevel = 2) -> 1810 return func (ax, * args, ** kwargs) 1811 1812 внутренний. документ = _add_data_doc (внутренний. документ ,

~ \ AppData \Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ axes_axes.py в scatter (self, x, y, s, c, маркер, cmap, норма, vmin, vmax, альфа, ширина линий, вершины, пограничные цвета, ** kwargs)4251
"или в виде чисел для сопоставления с цветами."4252
" Здесь c = {}. "# <- остерегайтесь, может быть длинным в зависимости от c. -> 4253 .format (c) 4254) 4255 else:

ValueError: аргумент 'c'должен быть действительным как цвета (цвета) mpl или как числа, которые должны быть сопоставлены с цветами. Здесь c = ['myLabel' 'myLabel' 'myLabel' ... 'myLabel' 'myLabel' 'myLabel'].

Здесь я использую код (из https://scikit -learn.org / stable / auto_examples / классификация / plot_classifier_comparison.html )

y = labels
X = features

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)

h = .02  # step size in the mesh
names = ["RBF SVM", "Random Forest", "Neural Net",
         "Naive Bayes"]
classifiers = [

    SVC(gamma=2, C=1),

    RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
    MLPClassifier(alpha=1),
    GaussianNB()
]

linearly_separable = (X, y)

datasets = [make_moons(noise=0.3, random_state=0),
            make_circles(noise=0.2, factor=0.5, random_state=1),
            linearly_separable
            ]

figure=plt.figure(figsize=[40,20])

i = 1
# iterate over datasets
for ds_cnt, ds in enumerate(datasets):
    # preprocess dataset, split into training and test part
    X, y = ds
    X = StandardScaler().fit_transform(X)
    X_train, X_test, y_train, y_test = \
        train_test_split(X, y, test_size=.4, random_state=42)

    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    # just plot the dataset first
    cm = plt.cm.RdBu
    cm_bright = ListedColormap(['#FF0000', '#0000FF'])
    ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
    if ds_cnt == 0:
        ax.set_title("Input data")
    # Plot the training points
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright,
               edgecolors='k')
    # Plot the testing points
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6,
               edgecolors='k')
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())
    i += 1

    # iterate over classifiers
    for name, clf in zip(names, classifiers):
        ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
        clf.fit(X_train, y_train)
        score = clf.score(X_test, y_test)

        # Plot the decision boundary. For that, we will assign a color to each
        # point in the mesh [x_min, x_max]x[y_min, y_max].
        if hasattr(clf, "decision_function"):
            Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
        else:
            Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]

        # Put the result into a color plot
        Z = Z.reshape(xx.shape)
        ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)

        # Plot the training points
        ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright,
                   edgecolors='k')
        # Plot the testing points
        ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
                   edgecolors='k', alpha=0.6)

        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xticks(())
        ax.set_yticks(())
        if ds_cnt == 0:
            ax.set_title(name)
        ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
                size=15, horizontalalignment='right')
        i += 1

plt.tight_layout()
plt.show()

Я также получаю изображение1. image1

Но я ожидаю что-то вроде image2: image2

...