创建图时如何解决关键错误?

问题描述 投票:1回答:1

我正在比较自己的数据集中的多个分类器。在进行绘图时,出现错误:

KeyError Traceback(最近的呼叫持续)〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ colors.py在to_rgba(c,alpha)中173尝试:-> 174 rgba = _colors_full_map.cache [c,alpha]175除外((KeyError,TypeError):#不在缓存中,或不可散列。

KeyError:('myLabel',无)

在处理以上异常期间,发生了另一个异常:

ValueError Traceback(最近的呼叫持续)〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ axes_axes.py在散点图(自我,x,y,s,c,标记,cmap,范数,vmin,vmax,alpha,线宽,verts,edgecolors,** kwargs)4231试试:#那么'c'是否可以用作PathCollection facecolors?-> 4232颜色= 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)中对于枚举(c)中的cc,为274:-> 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试试:

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ colors.py在_to_rgba_no_colorcycle(c,alpha)中219通过-> 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')2425

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib__init __。py在内部(ax,data,* args,** kwargs)1808“ Matplotlib列表!)”%(label_namer,func。name),1809年RuntimeWarning,堆栈级别= 2)-> 1810 return func(ax,* args,** kwargs)1811 1812内部。doc = _add_data_doc(inner。doc

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ matplotlib \ axes_axes.py在散点图(自我,x,y,s,c,标记,cmap,范数,vmin,vmax,alpha,线宽,verts,edgecolors,** kwargs)4251“或作为要映射到颜色的数字。” 4252“这里c = {}。” # 4253 .format(c)4254)4255其他:

ValueError:'c'参数必须作为mpl color(s)有效或作为要映射到颜色的数字。这里c = ['myLabel''myLabel''myLabel'...'myLabel''myLabel''myLabel']。

这里是我使用的代码(来自https://scikit-learn.org/stable/auto_examples/classification/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

python matplotlib scikit-learn keyerror
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.