我有这部分代码。
import matplotlib.pyplot as plt
for i in range(1, 5, 1):
x, y = valid_gen.__getitem__(i)
result = model.predict(x)
result = result > 0.4
for i in range(len(result)):
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax = fig.add_subplot(1, 2, 1)
ax.imshow(np.reshape(y[i] * 255, (image_size, image_size)), cmap="gray")
ax = fig.add_subplot(1, 2, 2)
ax.imshow(np.reshape(result[i] * 255, (image_size, image_size)), cmap="gray")
但当我试图绘制它时,我收到一个错误。
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory.
所以我想保存数字而不是绘制它,我应该怎么做?
解决方案:
首先,修改内循环的索引。目前它和外循环的索引是一样的,你不希望这样。将其设置为 j
比如说。
关于你的数字问题,在你的内循环中附加以下内容。
fig.savefig(f'Figure{i}_{j}.png')
plt.close(fig)
EDIT:
import matplotlib.pyplot as plt
import numpy as np
for i in range(1, 5, 1):
x, y = valid_gen.__getitem__(i)
result = model.predict(x)
result = result > 0.4
for j in range(len(result)):
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax = fig.add_subplot(1, 2, 1)
ax.imshow(np.reshape(y[j] * 255, (image_size, image_size)),
cmap='gray')
ax = fig.add_subplot(1, 2, 2)
ax.imshow(np.reshape(result[j] * 255, (image_size, image_size)),
cmap='gray')
fig.savefig(f'Figure{i}_{j}.png')
plt.close(fig)