How can I visualization CNN filters?

I got first conv2d filter’s weight values like this:

params = list(model.parameters())
params[0][0] # conv1's weight
tensor([[[-0.1867,  0.0042,  0.1249],
         [-0.0697, -0.1647,  0.0485],
         [ 0.0495, -0.0616,  0.1093]],

        [[ 0.1271,  0.1147,  0.1118],
         [-0.0211,  0.0898,  0.1344],
         [ 0.0735, -0.0565,  0.1802]],

        [[ 0.0370, -0.0470,  0.0933],
         [-0.1702, -0.0986, -0.1611],
         [ 0.0910, -0.0619, -0.0874]]], device='cuda:0',
       grad_fn=<SelectBackward>)

After this, I run under code to see filter, but the error occured.
How can I solve this?

plt.imshow(params[0][0])
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-63-931c8ef87f84> in <module>
----> 1 plt.imshow(params[0][0])

/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)
   2697         filternorm=filternorm, filterrad=filterrad, imlim=imlim,
   2698         resample=resample, url=url, **({"data": data} if data is not
-> 2699         None else {}), **kwargs)
   2700     sci(__ret)
   2701     return __ret

/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1808                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1809                         RuntimeWarning, stacklevel=2)
-> 1810             return func(ax, *args, **kwargs)
   1811 
   1812         inner.__doc__ = _add_data_doc(inner.__doc__,

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
   5492                               resample=resample, **kwargs)
   5493 
-> 5494         im.set_data(X)
   5495         im.set_alpha(alpha)
   5496         if im.get_clip_path() is None:

/usr/local/lib/python3.5/dist-packages/matplotlib/image.py in set_data(self, A)
    628         A : array-like
    629         """
--> 630         self._A = cbook.safe_masked_invalid(A, copy=True)
    631 
    632         if (self._A.dtype != np.uint8 and

/usr/local/lib/python3.5/dist-packages/matplotlib/cbook/__init__.py in safe_masked_invalid(x, copy)
    782 
    783 def safe_masked_invalid(x, copy=False):
--> 784     x = np.array(x, subok=True, copy=copy)
    785     if not x.dtype.isnative:
    786         # Note that the argument to `byteswap` is 'inplace',

~/.local/lib/python3.5/site-packages/torch/tensor.py in __array__(self, dtype)
    448     def __array__(self, dtype=None):
    449         if dtype is None:
--> 450             return self.numpy()
    451         else:
    452             return self.numpy().astype(dtype, copy=False)

RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

Hi,
Your tensor is a CUDA tensor so you can’t use matplotlib directly.
try:

plt.imshow(params[0][0].detach().cpu().numpy())

It should work

1 Like

@AnBucquet
It works!!
Thank you so much^^.

1 Like