Debian Codegraph @

bqplot/examples/Applications/Neural Network.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "This application demonstrates how to build a simple neural network using the Graph mark. \n",
8 "Interactions can be enabled by adding event handlers (click, hover etc) on the nodes of the network. \n",
9 "See the [Mark Interactions notebook](../Interactions/Mark%20Interactions.ipynb) and the [Scatter Notebook](../Marks/Object%20Model/Scatter.ipynb) for details."
10 ]
11 },
12 {
13 "cell_type": "code",
14 "execution_count": 4,
15 "metadata": {},
16 "outputs": [],
17 "source": [
18 "from itertools import chain, product\n",
19 "\n",
20 "import numpy as np\n",
21 "from bqplot import LinearScale, Graph, Figure"
22 ]
23 },
24 {
25 "cell_type": "code",
26 "execution_count": 5,
27 "metadata": {},
28 "outputs": [],
29 "source": [
30 "class NeuralNet(Figure):\n",
31 " def __init__(self, **kwargs):\n",
32 " self.height = kwargs.get('height', 600)\n",
33 " self.width = kwargs.get('width', 960)\n",
34 " self.directed_links = kwargs.get('directed_links', False)\n",
35 " \n",
36 " self.num_inputs = kwargs['num_inputs']\n",
37 " self.num_hidden_layers = kwargs['num_hidden_layers']\n",
38 " self.nodes_output_layer = kwargs['num_outputs']\n",
39 " self.layer_colors = kwargs.get('layer_colors', \n",
40 " ['Orange'] * (len(self.num_hidden_layers) + 2))\n",
41 " \n",
42 " self.build_net()\n",
43 " super(NeuralNet, self).__init__(**kwargs)\n",
44 " \n",
45 " def build_net(self):\n",
46 " # create nodes\n",
47 " self.layer_nodes = []\n",
48 " self.layer_nodes.append(['x' + str(i+1) for i in range(self.num_inputs)])\n",
49 " \n",
50 " for i, h in enumerate(self.num_hidden_layers):\n",
51 " self.layer_nodes.append(['h' + str(i+1) + ',' + str(j+1) for j in range(h)])\n",
52 " self.layer_nodes.append(['y' + str(i+1) for i in range(self.nodes_output_layer)])\n",
53 " \n",
54 " self.flattened_layer_nodes = list(chain(*self.layer_nodes))\n",
55 " \n",
56 " # build link matrix\n",
57 " i = 0\n",
58 " node_indices = {}\n",
59 " for layer in self.layer_nodes:\n",
60 " for node in layer:\n",
61 " node_indices[node] = i\n",
62 " i += 1\n",
63 "\n",
64 " n = len(self.flattened_layer_nodes)\n",
65 " self.link_matrix = np.empty((n,n))\n",
66 " self.link_matrix[:] = np.nan\n",
67 "\n",
68 " for i in range(len(self.layer_nodes) - 1):\n",
69 " curr_layer_nodes_indices = [node_indices[d] for d in self.layer_nodes[i]]\n",
70 " next_layer_nodes = [node_indices[d] for d in self.layer_nodes[i+1]]\n",
71 " for s, t in product(curr_layer_nodes_indices, next_layer_nodes):\n",
72 " self.link_matrix[s, t] = 1\n",
73 " \n",
74 " # set node x locations\n",
75 " self.nodes_x = np.repeat(np.linspace(0, 100, \n",
76 " len(self.layer_nodes) + 1, \n",
77 " endpoint=False)[1:], \n",
78 " [len(n) for n in self.layer_nodes])\n",
79 "\n",
80 " # set node y locations\n",
81 " self.nodes_y = np.array([])\n",
82 " for layer in self.layer_nodes:\n",
83 " n = len(layer)\n",
84 " ys = np.linspace(0, 100, n+1, endpoint=False)[1:]\n",
85 " self.nodes_y = np.append(self.nodes_y, ys[::-1])\n",
86 " \n",
87 " # set node colors\n",
88 " n_layers = len(self.layer_nodes)\n",
89 " self.node_colors = np.repeat(np.array(self.layer_colors[:n_layers]), \n",
90 " [len(layer) for layer in self.layer_nodes]).tolist()\n",
91 " \n",
92 " xs = LinearScale(min=0, max=100)\n",
93 " ys = LinearScale(min=0, max=100)\n",
94 " \n",
95 " self.graph = Graph(node_data=[{'label': d, \n",
96 " 'label_display': 'none'} for d in self.flattened_layer_nodes], \n",
97 " link_matrix=self.link_matrix, \n",
98 " link_type='line',\n",
99 " colors=self.node_colors,\n",
100 " directed=self.directed_links,\n",
101 " scales={'x': xs, 'y': ys}, \n",
102 " x=self.nodes_x, \n",
103 " y=self.nodes_y,\n",
104 " # color=2 * np.random.rand(len(self.flattened_layer_nodes)) - 1\n",
105 " )\n",
106 " self.graph.hovered_style = {'stroke': '1.5'}\n",
107 " self.graph.unhovered_style = {'opacity': '0.4'}\n",
108 " \n",
109 " self.graph.selected_style = {'opacity': '1',\n",
110 " 'stroke': 'red',\n",
111 " 'stroke-width': '2.5'}\n",
112 " self.marks = [self.graph]\n",
113 " self.title = 'Neural Network'\n",
114 " self.layout.width = str(self.width) + 'px'\n",
115 " self.layout.height = str(self.height) + 'px'"
116 ]
117 },
118 {
119 "cell_type": "code",
120 "execution_count": 6,
121 "metadata": {},
122 "outputs": [
123 {
124 "data": {
125 "application/vnd.jupyter.widget-view+json": {
126 "model_id": "b2d75468c39d4bcf896561f72febb74d",
127 "version_major": 2,
128 "version_minor": 0
129 },
130 "text/plain": [
131 "NeuralNet(fig_margin={'top': 60, 'bottom': 60, 'left': 60, 'right': 60}, layout=Layout(height='600px', width='…"
132 ]
133 },
134 "metadata": {},
135 "output_type": "display_data"
136 }
137 ],
138 "source": [
139 "NeuralNet(num_inputs=3, num_hidden_layers=[10, 10, 8, 5], num_outputs=1)"
140 ]
141 }
142 ],
143 "metadata": {
144 "input_collapsed": false,
145 "kernelspec": {
146 "display_name": "Python 3",
147 "language": "python",
148 "name": "python3"
149 },
150 "language_info": {
151 "codemirror_mode": {
152 "name": "ipython",
153 "version": 3
154 },
155 "file_extension": ".py",
156 "mimetype": "text/x-python",
157 "name": "python",
158 "nbconvert_exporter": "python",
159 "pygments_lexer": "ipython3",
160 "version": "3.7.6"
161 }
162 },
163 "nbformat": 4,
164 "nbformat_minor": 2
165 }