neural-lab 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
neural_lab/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .layer import Layer
2
+ from .network import Network
3
+ from .neuron import Neuron
neural_lab/layer.py ADDED
@@ -0,0 +1,23 @@
1
+ from math import isfinite
2
+ from typing import Self
3
+ from random import Random
4
+
5
+ from neural_lab.neuron import Neuron
6
+
7
+
8
+ class Layer:
9
+ def __init__(self, neurons: list[Neuron], step: float | None = None):
10
+ if step is not None and (not isfinite(step) or step <= 0):
11
+ raise ValueError("step must be finite and positive")
12
+ self.neurons = neurons
13
+ self.step = step
14
+ for neuron in neurons:
15
+ if neuron.step is None:
16
+ neuron.step = step
17
+
18
+ def connect(self, layer: Self, rng: Random | None = None) -> None:
19
+ for receiver in layer.neurons:
20
+ for source in self.neurons:
21
+ if source not in receiver.weights:
22
+ weight = rng.uniform(-0.1, 0.1) if rng is not None else None
23
+ source.connectRHS(receiver, weight)
neural_lab/network.py ADDED
@@ -0,0 +1,74 @@
1
+ from math import isfinite
2
+ from random import Random
3
+
4
+ from neural_lab.layer import Layer
5
+ from neural_lab.neuron import Neuron
6
+
7
+
8
+ class Network:
9
+ def __init__(self, layers: list[Layer], seed: int | None = None):
10
+ if len(layers) < 2 or any(not layer.neurons for layer in layers):
11
+ raise ValueError("Provide at least two nonempty layers")
12
+ neurons = [neuron for layer in layers for neuron in layer.neurons]
13
+ if len(set(neurons)) != len(neurons):
14
+ raise ValueError("Each neuron must appear exactly once")
15
+ self.layers = layers
16
+ self.input_layer = layers[0]
17
+ self.output_layer = layers[-1]
18
+ rng = Random(seed)
19
+ for source, receiver in zip(layers, layers[1:]):
20
+ source.connect(receiver, rng)
21
+
22
+ def predict(self, X: list[float]) -> list[float]:
23
+ if len(X) != len(self.input_layer.neurons):
24
+ raise ValueError("Supply one input value per input neuron")
25
+
26
+ # Check manual connection edits before using the layer traversal order.
27
+ positions = {neuron: index for index, layer in enumerate(self.layers)
28
+ for neuron in layer.neurons}
29
+ if len(positions) != sum(len(layer.neurons) for layer in self.layers):
30
+ raise ValueError("Each neuron must appear exactly once")
31
+ for receiver, index in positions.items():
32
+ for source in receiver.neuronsLHS:
33
+ if source not in positions or positions[source] >= index:
34
+ raise ValueError("Connections must run from earlier to later layers")
35
+ if any(target not in positions for target in receiver.neuronsRHS):
36
+ raise ValueError("All connected neurons must belong to this network")
37
+
38
+ # Input neurons hold data directly; they have no trainable parameters.
39
+ for neuron, value in zip(self.input_layer.neurons, X):
40
+ neuron.value = value
41
+ for layer in self.layers[1:]:
42
+ for neuron in layer.neurons:
43
+ neuron.activate()
44
+ return [neuron.value for neuron in self.output_layer.neurons]
45
+
46
+ def train(self, X_train: list[float], y_train: list[float]) -> None:
47
+ """One SGD step for loss = sum((prediction - target)**2) / 2."""
48
+ if len(y_train) != len(self.output_layer.neurons):
49
+ raise ValueError("Supply one target value per output neuron")
50
+ for layer in self.layers[1:]:
51
+ for neuron in layer.neurons:
52
+ if neuron.step is None or not isfinite(neuron.step) or neuron.step <= 0:
53
+ raise ValueError("Every computational neuron needs a finite, positive step")
54
+ self.predict(X_train)
55
+
56
+ # Clear all gradients, including those accumulated at input neurons.
57
+ for layer in self.layers:
58
+ for neuron in layer.neurons:
59
+ neuron.gradient = 0.0
60
+ neuron.delta = 0.0
61
+ for neuron, target in zip(self.output_layer.neurons, y_train):
62
+ neuron.gradient = neuron.value - target
63
+
64
+ # Each receiver adds its contribution before its sources propagate.
65
+ for layer in reversed(self.layers[1:]):
66
+ for neuron in layer.neurons:
67
+ neuron.propagate()
68
+
69
+ # Only now update parameters: the backward pass used the old weights.
70
+ for layer in self.layers[1:]:
71
+ for neuron in layer.neurons:
72
+ for source in neuron.weights:
73
+ neuron.weights[source] -= neuron.step * neuron.delta * source.value
74
+ neuron.bias -= neuron.step * neuron.delta
neural_lab/neuron.py ADDED
@@ -0,0 +1,59 @@
1
+ from math import isfinite, tanh
2
+ from random import uniform
3
+ from typing import Self
4
+
5
+
6
+ class Neuron:
7
+ """One weight per incoming connection, one bias, and an activation."""
8
+
9
+ def __init__(self, bias: float = 0, step: float | None = None,
10
+ name=None, activation: str = "linear"):
11
+ if activation not in ("linear", "tanh"):
12
+ raise ValueError("activation must be 'linear' or 'tanh'")
13
+ if step is not None and (not isfinite(step) or step <= 0):
14
+ raise ValueError("step must be finite and positive")
15
+ self.bias = bias
16
+ self.step = step
17
+ self.name = name
18
+ self.activation = activation
19
+ self.weights: dict[Self, float] = {}
20
+ self.neuronsRHS: list[Self] = []
21
+ self.value = 0.0
22
+ self.gradient = 0.0 # d(loss) / d(output)
23
+ self.delta = 0.0 # d(loss) / d(weighted sum)
24
+
25
+ @property
26
+ def neuronsLHS(self) -> list[Self]:
27
+ return list(self.weights)
28
+
29
+ def connectRHS(self, neuronRHS: Self, weight: float | None = None) -> None:
30
+ if neuronRHS is self:
31
+ raise ValueError("A neuron cannot connect to itself")
32
+ if neuronRHS not in self.neuronsRHS:
33
+ self.neuronsRHS.append(neuronRHS)
34
+ neuronRHS.weights[self] = uniform(-0.1, 0.1) if weight is None else weight
35
+
36
+ def connectLHS(self, neuronLHS: Self, weight: float | None = None) -> None:
37
+ neuronLHS.connectRHS(self, weight)
38
+
39
+ def disconnectRHS(self, neuronRHS: Self) -> None:
40
+ """Remove just this edge and its weight; save the weight before reconnecting."""
41
+ if neuronRHS in self.neuronsRHS:
42
+ self.neuronsRHS.remove(neuronRHS)
43
+ del neuronRHS.weights[self]
44
+
45
+ def disconnectLHS(self, neuronLHS: Self) -> None:
46
+ neuronLHS.disconnectRHS(self)
47
+
48
+ def activate(self) -> None:
49
+ total = self.bias
50
+ for source, weight in self.weights.items():
51
+ total += source.value * weight
52
+ self.value = tanh(total) if self.activation == "tanh" else total
53
+
54
+ def propagate(self) -> None:
55
+ """Pass gradients backward without changing any parameters."""
56
+ derivative = 1 - self.value ** 2 if self.activation == "tanh" else 1.0
57
+ self.delta = self.gradient * derivative
58
+ for source, weight in self.weights.items():
59
+ source.gradient += self.delta * weight
@@ -0,0 +1,283 @@
1
+ Metadata-Version: 2.5
2
+ Name: neural-lab
3
+ Version: 0.5.0
4
+ Summary: A neural network implementation built as an explicit graph of neurons and weighted connections.
5
+ Project-URL: Homepage, https://github.com/adamjpatterson/neural-lab
6
+ Project-URL: Issues, https://github.com/adamjpatterson/neural-lab/issues
7
+ Author-email: FAR Analytics & Research <adpatter2000@gmail.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Neural Lab
16
+
17
+ [![PyPI version](https://img.shields.io/pypi/v/neural-lab.svg)](https://pypi.org/project/neural-lab/) [![Python versions](https://img.shields.io/pypi/pyversions/neural-lab.svg)](https://pypi.org/project/neural-lab/) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/adamjpatterson/neural-lab/blob/main/LICENSE)
18
+
19
+ A neural network implementation built as an explicit graph of neurons and weighted connections.
20
+
21
+ ## Introduction
22
+
23
+ **Neural Lab** represents individual neurons and their connections explicitly. Backpropagation is done using explicitly computed gradients. The object-oriented API consists of Network, Layer, and Neuron constructors. The networks can be easily [visualized](#visualizations-of-the-network-before-and-after-training) using a visualization library.
24
+
25
+ ## Table of contents
26
+
27
+ - [Installation](#installation)
28
+ - [How it works](#how-it-works)
29
+ - [Examples](#examples)
30
+ - [The nibble challenge](#the-nibble-challenge)
31
+ - [The digits experiment](#the-digits-experiment)
32
+ - [Tests](#tests)
33
+ - [Documentation maintenance](#documentation-maintenance)
34
+
35
+ ## Installation
36
+
37
+ To use the published package:
38
+
39
+ ```bash
40
+ python -m pip install neural-lab
41
+ ```
42
+
43
+ ## How it works
44
+
45
+ This implementation demonstrates each component of the API. A 3 layer neural network is constructed that has a 4 neuron input Layer and a 1 neuron output layer. The hidden layer has 8 neurons.
46
+
47
+ ### Implement a 3 layer neural network
48
+
49
+ #### Import the Network, Layer, and Neuron classes.
50
+
51
+ ```python
52
+ from neural_lab import Network, Layer, Neuron
53
+ ```
54
+
55
+ #### Set a step.
56
+
57
+ `step` is the learning rate: it controls the size of weight and bias updates. Each update subtracts `step` times the corresponding gradient. `Layer(step=...)` supplies an initial default only to neurons whose `step` is `None`. Changing `layer.step` later does not change the neurons; update each `neuron.step` directly to change its learning rate.
58
+
59
+ ```python
60
+ STEP = 0.01
61
+ ```
62
+
63
+ #### Construct a neural network by specifying the Neurons for each Layer and adding the Layers to a Network.
64
+
65
+ ```python
66
+ l1 = Layer(neurons=[Neuron() for i in range(0, 4)], step=STEP)
67
+ l2 = Layer(neurons=[Neuron() for i in range(0, 8)], step=STEP)
68
+ l3 = Layer(neurons=[Neuron()], step=STEP)
69
+ n1 = Network([l1, l2, l3], seed=42)
70
+ ```
71
+
72
+ #### With the Network defined, you can train the network.
73
+
74
+ Here the network is trained to recognize the nibble 1111 as the decimal number 15.
75
+
76
+ ```python
77
+ n1.train([1,1,1,1], [15])
78
+ ```
79
+
80
+ You can generate and print a prediction using the `predict` method. Because the network underwent just one iteration of training, the estimate will likely be inaccurate. The accuracy of the prediction can be improved by iteratively training the network. Please see [the nibble challenge](#the-nibble-challenge) for an example of how to iteratively train the network.
81
+
82
+ ```python
83
+ prediction = n1.predict([1,1,1,1])
84
+ print(prediction)
85
+ ```
86
+
87
+ ### How a neuron learns
88
+
89
+ Consider the training call from the example above:
90
+
91
+ ```python
92
+ n1.train([1, 1, 1, 1], [15])
93
+ ```
94
+
95
+ The four inputs are the bits of `1111`; the target output is `15`. Here is how this one call changes the network. The excerpts below come from `Network` and `Neuron`.
96
+
97
+ #### 1. Calculate a prediction
98
+
99
+ `train` checks that there is one target per output neuron and that every non-input neuron has a finite, positive learning rate (`step`). It then calls:
100
+
101
+ ```python
102
+ self.predict(X_train)
103
+ ```
104
+
105
+ `predict` checks the inputs and connections, assigns the four input values, and calls `activate` on each hidden neuron, then the output neuron. Inside `Neuron.activate`:
106
+
107
+ ```python
108
+ total = self.bias
109
+ for source, weight in self.weights.items():
110
+ total += source.value * weight
111
+ self.value = tanh(total) if self.activation == "tanh" else total
112
+ ```
113
+
114
+ Each neuron adds its bias to the weighted inputs and stores its activation in `value`. This example uses linear activation, so `value` is simply `total`. Hidden neurons can also use `tanh`.
115
+
116
+ #### 2. Clear old gradients and calculate the output error
117
+
118
+ Back in `train`, gradients from the previous call are cleared before calculating the output gradients:
119
+
120
+ ```python
121
+ for layer in self.layers:
122
+ for neuron in layer.neurons:
123
+ neuron.gradient = 0.0
124
+ neuron.delta = 0.0
125
+ for neuron, target in zip(self.output_layer.neurons, y_train):
126
+ neuron.gradient = neuron.value - target
127
+ ```
128
+
129
+ The loss is half the sum of squared output errors. A neuron's `gradient` is the derivative of that loss with respect to its output. For our output neuron, this starts as the prediction minus `15`.
130
+
131
+ #### 3. Propagate gradients backward
132
+
133
+ `train` visits the output layer first, then the hidden layers:
134
+
135
+ ```python
136
+ for layer in reversed(self.layers[1:]):
137
+ for neuron in layer.neurons:
138
+ neuron.propagate()
139
+ ```
140
+
141
+ Inside `Neuron.propagate`:
142
+
143
+ ```python
144
+ derivative = 1 - self.value ** 2 if self.activation == "tanh" else 1.0
145
+ self.delta = self.gradient * derivative
146
+ for source, weight in self.weights.items():
147
+ source.gradient += self.delta * weight
148
+ ```
149
+
150
+ `delta` is the derivative of the loss with respect to the weighted sum plus bias, before activation. For linear activation, the derivative is `1`, so `delta` equals `gradient`. Each neuron passes a contribution back through each incoming connection. The `+=` lets a source accumulate contributions from every neuron it feeds. Visiting layers in reverse ensures those contributions arrive before the source propagates its own gradient.
151
+
152
+ #### 4. Update weights and biases
153
+
154
+ Only after the backward pass finishes does `train` change the parameters:
155
+
156
+ ```python
157
+ for layer in self.layers[1:]:
158
+ for neuron in layer.neurons:
159
+ for source in neuron.weights:
160
+ neuron.weights[source] -= neuron.step * neuron.delta * source.value
161
+ neuron.bias -= neuron.step * neuron.delta
162
+ ```
163
+
164
+ A weight's gradient is `delta * source.value`; the bias gradient is `delta`. Subtracting `step` times each gradient updates the parameters. Waiting until this point means every backward calculation uses the same weights as the forward pass. The next call to `predict` uses the updated weights and biases.
165
+
166
+ Each incoming connection has its own weight in `neuron.weights[source]`. `Neuron(bias=...)` sets the initial bias, and `Network(..., seed=42)` initializes weights reproducibly in [-0.1, 0.1]. Connections added later accept an explicit `weight`; repeated connection calls preserve existing weights.
167
+
168
+ ### Explore a trained network
169
+
170
+ After training, remove a connection and compare predictions to see how it affects the network. This experiment is called an ablation.
171
+
172
+ Using your trained network as `n1`:
173
+
174
+ ```python
175
+ inputs = [1, 0, 1, 0]
176
+ source = n1.layers[1].neurons[0]
177
+ receiver = n1.output_layer.neurons[0]
178
+ weight = receiver.weights[source]
179
+ before = n1.predict(inputs)
180
+
181
+ source.disconnectRHS(receiver)
182
+ after = n1.predict(inputs)
183
+ print("Original prediction:", before)
184
+ print("Without the connection:", after)
185
+
186
+ source.connectRHS(receiver, weight=weight)
187
+ ```
188
+
189
+ Try several inputs: a connection's effect can depend on the input.
190
+
191
+ You can also change an existing weight through `receiver.weights[source]`. Use the connection methods to add or remove edges so incoming weights and outgoing connections stay consistent.
192
+
193
+ ## Examples
194
+
195
+ ### The nibble challenge
196
+
197
+ #### Setup
198
+
199
+ Change directory into the example project from the repository root.
200
+
201
+ ```
202
+ cd examples/the_nibble_challenge
203
+ ```
204
+
205
+ Install the example dependencies.
206
+
207
+ ```
208
+ pip install .
209
+ ```
210
+
211
+ #### Explore the notebook
212
+
213
+ Open [the nibble challenge notebook](https://github.com/adamjpatterson/neural-lab/blob/main/examples/the_nibble_challenge/main.ipynb). It introduces all sixteen four-bit inputs, constructs a 4 → 8 → 1 network, compares initial and trained predictions, and lets you change an input to inspect weights and activations. With seed 42, a step of 0.01, and 10,000 training examples, the displayed R² rounds to 1.000000000.
214
+
215
+ The network learns a simple linear relationship. Training and evaluation both use all sixteen nibbles; hence, the experiment does not provide evidence of generalization. The notebook imports `visualize_network` from [its visualization module](https://github.com/adamjpatterson/neural-lab/blob/main/examples/the_nibble_challenge/visualizations.py).
216
+
217
+ ##### Visualizations of the network before and after training
218
+
219
+ ![Nibble network before and after training](https://raw.githubusercontent.com/adamjpatterson/neural-lab/main/images/nibble_multiweight.png)
220
+
221
+ - Edge thickness is proportional to the absolute connection weight. Blue is positive; orange is negative. Zero-weight edges have zero width.
222
+ - Node area above a small visibility floor is proportional to absolute activation. Green nodes are inputs, red nodes are hidden, and yellow is the output.
223
+ - Both panels use the same input, positions, and scales. Node size represents activity, not importance, and does not encode the activation's sign.
224
+
225
+ This visualization demonstrates that an irregular-looking network can learn a simple mapping almost perfectly: individual connections can reinforce or cancel one another.
226
+
227
+ ### The digits experiment
228
+
229
+ #### Setup
230
+
231
+ Change directory into the example project from the repository root.
232
+
233
+ ```bash
234
+ cd examples/the_digits_experiment
235
+ ```
236
+
237
+ Install the example dependencies.
238
+
239
+ ```bash
240
+ pip install .
241
+ ```
242
+
243
+ #### Explore the notebook
244
+
245
+ Open [the digits experiment notebook](https://github.com/adamjpatterson/neural-lab/blob/main/examples/the_digits_experiment/main.ipynb). It starts by displaying the [8×8 digits dataset](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html), then normalizes pixels, creates a training/test split, constructs a 64 → 16 → 10 network, trains, and evaluates unseen images. You can inspect an individual prediction and its ten output scores. Scores are not probabilities.
246
+
247
+ The reproducible settings use seed 42, 1,347 training images, 450 test images, 20 epochs, and a step of 0.001. The example achieves **90.22% test accuracy**, compared with **10.22%** for always predicting the most common training digit.
248
+
249
+ The notebook imports `plot_predictions` and `plot_confusion_matrix` from [its visualization module](https://github.com/adamjpatterson/neural-lab/blob/main/examples/the_digits_experiment/visualizations.py).
250
+
251
+ #### Digits predictions and confusion matrix
252
+
253
+ The prediction figure shows the first twelve test images. The confusion matrix includes all 450 test images; rows show the true digit and columns show the predicted digit.
254
+
255
+ ![Digits predictions and confusion matrix](https://raw.githubusercontent.com/adamjpatterson/neural-lab/main/images/digits_results.png)
256
+
257
+ ## Tests
258
+
259
+ The suite in `tests/test.py` checks forward calculations, manual gradients, parameter updates, connection removal and restoration, and input validation.
260
+
261
+ #### Run all tests.
262
+
263
+ ```bash
264
+ python -m unittest -v
265
+ ```
266
+
267
+ ## Documentation maintenance
268
+
269
+ ### Regenerating README figures
270
+
271
+ The [documentation-image project](https://github.com/adamjpatterson/neural-lab/blob/main/docs/README.md) has its own dependencies and fixed seed-42 scenarios. From `docs/`, after following its environment setup:
272
+
273
+ ```bash
274
+ python generate_images.py
275
+ ```
276
+
277
+ It writes the nibble network image and the combined digits predictions and confusion matrix image to `images/`.
278
+
279
+ ## Support
280
+
281
+ If you have a feature request or run into any issues, feel free to submit an [issue](https://github.com/adamjpatterson/neural-lab/issues). You’re also welcome to reach out to one of the authors.
282
+
283
+ - [Adam Patterson](https://github.com/adamjpatterson)
@@ -0,0 +1,9 @@
1
+ neural_lab/__about__.py,sha256=LBK46heutvn3KmsCrKIYu8RQikbfnjZaj2xFrXaeCzQ,22
2
+ neural_lab/__init__.py,sha256=MDi8Jpgf1gkzlUC3JGSrxgtXwPdGI0hCqJOQipB5TJU,81
3
+ neural_lab/layer.py,sha256=X7Y1f_GBoSF3Vtdmgob0BpiW3Q0kqe68hZpr21JIHuM,832
4
+ neural_lab/network.py,sha256=eM5A-MShM4zQItxmfX4NmWNbGzzh9VIPlMnjM4ubkXY,3572
5
+ neural_lab/neuron.py,sha256=S8EycxYovqK23jtZ3FWrQkOXwO6t9zkpU2BxTNsPo4k,2372
6
+ neural_lab-0.5.0.dist-info/METADATA,sha256=EvTUA1K_VfzzMYXuUHhH5vNNIVEbj69Ztxs0mYu59vE,12122
7
+ neural_lab-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ neural_lab-0.5.0.dist-info/licenses/LICENSE,sha256=C_XDFNZuiaBnTzrum_j7RmxlLLAby9rVu6vt1C9mwco,1081
9
+ neural_lab-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 FAR Analytics & Research
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.