This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Hinton diagrams with matplotlib

Hinton diagrams are a way of visualizing numerical values in a matrix/vector, popular in the neural networks and machine learning literature. The area occupied by a square is proportional to a value's magnitude, and the colour (black or white in this case) indicates its sign (positive/negative).

hinton.png

   1 import numpy as N
   2 import pylab as P
   3 
   4 def _blob(x,y,area,colour):
   5     """
   6     Draws a square-shaped blob with the given area (< 1) at
   7     the given coordinates.
   8     """
   9     hs = N.sqrt(area) / 2
  10     xcorners = N.array([x - hs, x + hs, x + hs, x - hs])
  11     ycorners = N.array([y - hs, y - hs, y + hs, y + hs])
  12     P.fill(xcorners, ycorners, colour, edgecolor=colour)
  13 
  14 def hinton(W, maxWeight=None):
  15     """
  16     Draws a Hinton diagram for visualizing a weight matrix. 
  17     Temporarily disables matplotlib interactive mode if it is on, 
  18     otherwise this takes forever.
  19     """
  20     reenable = False
  21     if P.isinteractive():
  22         P.ioff()
  23     P.clf()
  24     height, width = W.shape
  25     if not maxWeight:
  26         maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2))
  27         
  28     P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray')
  29     P.axis('off')
  30     P.axis('equal')
  31     for x in xrange(width):
  32         for y in xrange(height):
  33             _x = x+1
  34             _y = y+1
  35             w = W[y,x]
  36             if w > 0:
  37                 _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
  38             elif w < 0:
  39                 _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
  40     if reenable:
  41         P.ion()
  42     P.show()

SciPy: Cookbook/Matplotlib/HintonDiagrams (last edited 2015-10-24 17:48:26 by anonymous)