'Insert images from a collection to a matplotlib image matrix
I have a school assignment and I got stuck iterating over things.
I want to iterate on the mathplotlib images matrix and insert images from a generator I created.
# 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
the code I iterate with is obviously not good, but I can't figure out how to implement my desired iteration.
# 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}")
I hope the question is clear and understandable. I'd love to know if something is not 100% with the question for future improvements.
Thanks!
EDIT:
My goal is to insert every object from the generator to a single matrix cell.\
[What I get now is this (the last object from the generator in all matrix cell, when I want a different object in every cell):1
Solution 1:[1]
You can probably use something along the following lines:
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}")
That creates the iterator, but doesn't yet retrieve the data.
The next() function then advances the iterator each time inside the nested loop, retrieving the necessary items from the iterator.
Solution 2:[2]
Assuming that the number of images returned by your generator is the same as the number of axis of your figure, you can do something like this:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 9769953 |
| Solution 2 | Davide_sd |
