在Matplotlib中使用带有蒙版数组的多个颜色贴图和contourf

时间:2017-11-30 17:26:53

标签: python matplotlib

我试图在训练的渐进阶段期间在2D平面上可视化分类模型的输出。我生成具有四个类的模拟数据,并且模型生成softmax输出 - 对于网格中的每个数据点,模型产生长度为四的向量,例如:[0.1,0.5,0.2,0.2],代表性模型给出每个类中的数据点的概率。在这种情况下,我们会说模型预测数据点的第1类,因为这是四个中概率最高的。

我尝试做的是使用模型的预测和模型给出的概率来可视化分类器的决策边界。我希望,对于网格上的每个数据点,颜色代表模型预测的类,颜色的黑暗代表概率,0.25为白色,1.0为该梯度中最暗的颜色。 (0.25为白色,因为[0.25,0.25,0.25,0.25]是模型最混淆的)。我使用以下代码生成我的绘图,它比较了两个非常相似的模型:

f, (ax1, ax2) = plt.subplots(2, figsize=(4, 7), dpi=80, sharex=True,       sharey=True)
f.suptitle("Training Set and Decision Boundary, Batch={0}".format(batch))
f.tight_layout(rect=[0, 0.03, 1, 0.95])

cmaps = ["Purples","Greens","Oranges","Blues"]

ax1.set_title("Baseline Model")
ax1.set_xlim([-10,10])
ax1.set_ylim([-10,10])
ax2.set_title("Modified Model")
ax2.set_xlim([-10,10])
ax2.set_ylim([-10,10])

u = np.unique(p1)

# Loop through the predicted classes, using a masked array to set the points predicted to be that class

for i in range(len(u)):
    c = u[i]

    xx_tmp = np.ma.masked_array(xx, p1 == c)
    yy_tmp = np.ma.masked_array(yy, p1 == c)
    z_tmp = np.ma.masked_array(z1, p1 == c)

    ax1.contourf(xx_tmp, yy_tmp, z_tmp, cmap=cmaps[c])

u = np.unique(p2)

for i in range(len(u)):
    c = u[i]

    xx_tmp = np.ma.masked_array(xx, p2 == c)
    yy_tmp = np.ma.masked_array(yy, p2 == c)
    z_tmp = np.ma.masked_array(z2, p2 == c)

    ax2.contourf(xx_tmp, yy_tmp, z_tmp, cmap=cmaps[c])


plt.savefig(VIS_DIR + "Batch{0}.png".format(batch))
plt.gcf().clear()

我在100 x 100网格中使用10,000个点来提供contourf功能。 z1和z2是100×100个numpy阵列,其在每个数据点的预测矢量中存储最高概率。 p1和p2是100 x 100个数组,用于存储每个数据点的预测类(0,1,2,3)。

这段代码很有用,但出于某种原因,我最多只能获得两种颜色而且我不明白为什么(我已经验证了我的预测数组中有正确的标签)。以下是两个例子:

Plot output after batch 200

Plot output after batch 400

很容易看出决策界限在哪里,并且通过更多培训可以很容易地看到四个班级以及不断增加的模型信心。但为什么三个班级是蓝色的?我最多只能获得两种颜色。如果我重新排序cmaps列表中的颜色,那么我得到的颜色会发生变化,所以我认为它与matplotlib覆盖以前的传递有关。这里有什么不对的吗?我是否应该使用蒙面数组和contourf,或者有更简单的方法吗?

谢谢!

0 个答案:

没有答案