我使用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_ function。请帮助我必须编写的命令以使用命令而不是手动保存图形。因为如果有大型网络则有很多手工工作。
答案 0 :(得分:1)
我有一个类似的问题,试图用plt.savefig
在Keras中保存数据。
它总是导致空白图像。
我从来没有真正发现它为什么会发生,如果我没记错,它只会在使用多处理时发生,但我可能错了。
我使用非交互式后端解决了它,如果你永远不会用plt.show()
显示它们,那么无论如何都应该是正确的选择。
在matplotlib导入的顶部添加
import matplotlib as mpl
mpl.use('Agg')
另外,如果您在某些时候保存了许多这样的图像,matplotlib会抱怨太多的开放数字。您应该在每个plt.close()
之后添加plt.savefig
来电。
对于纯粹轶事的答案感到抱歉,也许有更好洞察力的人会发表评论。