我正在使用here中的代码来可视化我的cnn模型过滤器(内核),如下所示:

from mpl_toolkits.axes_grid1 import make_axes_locatable
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
#    pl.savefig("featuremaps--{}".format(layer_num) + '.jpg')

import numpy.ma as ma
def make_mosaic(imgs, nrows, ncols, border=1):
    """
    Given a set of images with all the same shape, makes a
    mosaic with nrows and ncols
    """
    nimgs = imgs.shape[0]
    imshape = imgs.shape[1:]

    mosaic = ma.masked_all((nrows * imshape[0] + (nrows - 1) * border,
                            ncols * imshape[1] + (ncols - 1) * border),
                            dtype=np.float32)

    paddedh = imshape[0] + border
    paddedw = imshape[1] + border
    for i in range(nimgs):
        row = int(np.floor(i / ncols))
        col = i % ncols

        mosaic[row * paddedh:row * paddedh + imshape[0],
               col * paddedw:col * paddedw + imshape[1]] = imgs[i]
    return mosaic


# Visualize weights
W=model.layers[8].get_weights()[0][:,:,0,:]
W=np.swapaxes(W,0,2)
W = np.squeeze(W)
print("W shape : ", W.shape)

pl.figure(figsize=(15, 15))
pl.title('conv1 weights')
nice_imshow(pl.gca(), make_mosaic(W, 8, 8), cmap=cm.binary)


我想保存过滤器图像。通常,我们使用fig.savefig("featuremaps-kernel-{}".format(layer_num) + '.jpg')保存数字。但这在这种情况下不起作用,可能是因为nice_函数。请帮助我必须写什么命令才能使用命令手动保存图形。因为如果有大型网络,则需要大量的手动工作。

最佳答案

我尝试使用plt.savefig将数据保存在Keras中时遇到类似的问题。
它总是导致空白图像。

我从来没有真正弄清楚它为什么会发生,如果我没记错的话,它只是在使用多处理时才发生,但是我可能是错的。

我使用非交互式后端解决了该问题,如果您永远不会用plt.show()显示它们,那么它应该是正确的选择。

在matplotlib导入的顶部添加

import matplotlib as mpl
mpl.use('Agg')


另外,如果您要在某个时候保存许多这样的图像,则matplotlib会抱怨打开的数字过多。您应该在每个plt.close()之后添加一个plt.savefig调用。

对纯轶事的答案感到抱歉,也许有更好见识的人会发表评论。

10-06 05:03
查看更多