将集合中的图像插入 matplotlib 图像矩阵

Insert images from a collection to a matplotlib image matrix

我有一项学校作业,但我一直在重复事情。
我想迭代 mathplotlib 图像矩阵并从我创建的生成器中插入图像。

# this is the generator, it yields back 2 integers (true_value and prediction)
# and a {64,} image shape (image)

def false_negative_generator(X_test, y_test, predicted):
    for image, true_value, prediction in zip(X_test, y_test, predicted):
        if true_value != prediction:
            yield image, true_value, prediction

我迭代的代码显然不好,但我想不出如何实现我想要的迭代。

# axrow is a row in the plot matrix, ax is a cell in the matrix
for image, lable, prediction in false_negative_generator(X_test, y_test, predicted):
    for axrow in axes:
        for ax in axrow:
            ax.set_axis_off()
            ax.imshow(image.reshape(8, 8), cmap=plt.cm.gray_r, interpolation="nearest")
            ax.set_title(f"{lable} {prediction}")

我希望问题清楚易懂。我很想知道未来改进的问题是否不是 100%。
谢谢!

编辑:

我的目标是将生成器中的每个对象插入到单个矩阵单元格中。\

[我现在得到的是这个(所有矩阵单元格中生成器的最后一个对象,当我想要每个单元格中的不同对象时):1

假设你的生成器返回的图像数量与你的图形的轴数相同,你可以这样做:

i = 0 # counter
axs = axes.flatten() # convert the grid of axes to an array
for image, lable, prediction in false_negative_generator(X_test, y_test, predicted):
    axs[i].set_axis_off()
    axs[i].imshow(image.reshape(8, 8), cmap=plt.cm.gray_r, interpolation="nearest")
    axs[i].set_title(f"{lable} {prediction}")
    i += 1

您或许可以使用以下几行内容:

iterator = false_negative_generator(X_test, y_test, predicted)
for axrow in axes:
    for ax in axrow:
       image, lable, prediction = next(iterator)
       ax.set_axis_off()
       ax.imshow(image.reshape(8, 8), cmap=plt.cm.gray_r, interpolation="nearest")
       ax.set_title(f"{lable} {prediction}")

创建迭代器,但尚未检索数据。 next() 函数然后每次在嵌套循环内推进迭代器,从迭代器中检索必要的项目。