{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Hinton diagrams\n\nHinton diagrams are useful for visualizing the values of a 2D array (e.g.\na weight matrix): Positive and negative values are represented by white and\nblack squares, respectively, and the size of each square represents the\nmagnitude of each value.\n\nInitial idea from David Warde-Farley on the SciPy Cookbook\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef hinton(matrix, max_weight=None, ax=None):\n    \"\"\"Draw Hinton diagram for visualizing a weight matrix.\"\"\"\n    ax = ax if ax is not None else plt.gca()\n\n    if not max_weight:\n        max_weight = 2 ** np.ceil(np.log2(np.abs(matrix).max()))\n\n    ax.patch.set_facecolor('gray')\n    ax.set_aspect('equal', 'box')\n    ax.xaxis.set_major_locator(plt.NullLocator())\n    ax.yaxis.set_major_locator(plt.NullLocator())\n\n    for (x, y), w in np.ndenumerate(matrix):\n        color = 'white' if w > 0 else 'black'\n        size = np.sqrt(abs(w) / max_weight)\n        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,\n                             facecolor=color, edgecolor=color)\n        ax.add_patch(rect)\n\n    ax.autoscale_view()\n    ax.invert_yaxis()\n\n\nif __name__ == '__main__':\n    # Fixing random state for reproducibility\n    np.random.seed(19680801)\n\n    hinton(np.random.rand(20, 20) - 0.5)\n    plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}