【问题标题】:Error with matplotlib scatter plot due to color palette由于调色板导致 matplotlib 散点图出错
【发布时间】:2021-06-26 00:46:36
【问题描述】:

我使用这种方法为 mnist 数据集的另一个模型创建了散点图,它适用于另一个模型,但我无法弄清楚我对另一个模型做错了什么。

方法是

def scatter(x, labels, subtitle=None):
    # Create a scatter plot of all the 
    # the embeddings of the model.
    # We choose a color palette with seaborn.
    palette = np.array(sns.color_palette("hls", 10))
    # We create a scatter plot.
    f = plt.figure(figsize=(8, 8))
    ax = plt.subplot(aspect='equal')
    sc = ax.scatter(x[:,0], x[:,1], lw=0,alpha = 0.5, s=40,
                c=palette[labels.astype(np.int)])
    plt.xlim(-25, 25)
    plt.ylim(-25, 25)
    ax.axis('off')
    ax.axis('tight')

我使用它来使用来自 keras 的 mnist 数据集为绘图创建数据

# Using the newly trained model compute the embeddings 
# for a number images
sample_size = 5000
X_train_trm = model.predict(X_train[:sample_size].reshape(-1,28,28,1))
X_test_trm = model.predict(X_test[:sample_size].reshape(-1,28,28,1))
# TSNE to use dimensionality reduction to visulaise the resultant embeddings
tsne = TSNE()
train_tsne_embeds = tsne.fit_transform(X_train_trm)
scatter(train_tsne_embeds, y_train[:sample_size])

这会给出这个错误,当我检查调色板和 c 的大小时我不明白它应该是 5000 而不是 150000。 错误是这样的

ValueError: 'c' argument has 150000 elements, which is inconsistent with 'x' and 'y' with size 5000.

【问题讨论】:

  • 应该叫ax.scatter(..., c=labels, cmap='hls')
  • 您还可以使用cmap = sns.color_palette('hls', as_cmap=True) 将 seaborn 调色板转换为 matplotlib 颜色图。虽然不是推荐的方法,但您的原始代码也应该适用于最新的 matplotlib 版本。

标签: python matplotlib keras scatter-plot


【解决方案1】:

经过一番谷歌搜索并遇到一些死插件后,我发现了问题所在。 我发布的代码工作正常。我使用的标签被转换为分类使用

y_train = keras.utils.to_categorical(y_train, 10)

这就是错误包含 150000 个元素的原因。这都是 onehot 编码。 为了解决这个问题,我在开始时复制了标签,然后用 onehot 对它们进行编码。

# convert class vectors to binary class matrices
Y_train_raw = y_train

y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)

然后在散点图中使用原始标签

scatter(train_tsne_embeds, Y_train_raw[:sample_size])

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 2021-07-28
    • 2020-12-30
    • 1970-01-01
    • 2014-09-10
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多