netlite 0.0.1__tar.gz → 0.0.2__tar.gz

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,3 @@
1
+ dist
2
+ __pycache__
3
+ mnist_raw
netlite-0.0.2/PKG-INFO ADDED
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: netlite
3
+ Version: 0.0.2
4
+ Summary: A small white-box training framework for neural networks for education.
5
+ Project-URL: Homepage, https://github.com/haho12/netlite
6
+ Project-URL: Issues, https://github.com/haho12/netlite/issues
7
+ Author-email: Hanno Homann <hanno.homann@example.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: gzip
14
+ Requires-Dist: matplotlib
15
+ Requires-Dist: numba
16
+ Requires-Dist: numpy
17
+ Requires-Dist: pickle
18
+ Requires-Dist: urllib
19
+ Description-Content-Type: text/markdown
20
+
21
+ # NetLite
22
+
23
+ **A small white-box training framework for neural networks for education.**
24
+
25
+ NetLite provides a light-weight training framework, designed for readability
26
+ for learning the basic principles of neural networks in AI classes.
27
+
28
+ **Performance:**
29
+ - On LeNet, this framework achieves 99% accuracy on the MNIST validation data in just 150 seconds (on my laptop cpu).
30
+ - computation using numpy for most operations
31
+ - just-in-time compilation using numba for convolutions
32
+ - Data-loader allows to limit the number of images used, e.g. to train on just 10% of the MNIST data,
33
+ for even faster training during lab exercises and to get a feeling for over-fitting when not enough data is available.
34
+
35
+ ![Accuracy curve](./images/lenet_mnist_acc_curves.svg)
36
+
37
+ **Fig. 1:** *Accuracy of LeNet5 trained using NetLite's ADAM optimizer.*
38
+
39
+ **Exemplary learning tasks for AI classes using this framework:**
40
+ - Take a given activation function (e.g. ReLU from layers.py) and use it as a template to create your own activation function (e.g. tanh).
41
+ - Implement a robust loss function (e.g. Huber loss) a fit a regression line to noisy data.
42
+ - Use debugger to step through optimization, compare with manual calculations.
43
+ - Understand and compare different optimizers (SGD, Momentum, ADAM).
44
+
45
+ ## Example 1: Training of a 2-layer model as an XOR classifier
46
+
47
+ ```Python
48
+ import numpy as np
49
+ import matplotlib.pyplot as plt
50
+
51
+ import netlite as nl
52
+
53
+ def train(model, optimizer, X_train, y_train, n_epochs=10, batchsize=32):
54
+ log = {}
55
+ log['loss_train'] = []
56
+ log['acc_train'] = []
57
+ for epoch in range(n_epochs):
58
+ loss_sum = 0
59
+ n_correct_sum = 0
60
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
61
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
62
+ loss_sum += loss
63
+ n_correct_sum += metrics['n_correct']
64
+
65
+ loss_train_mean = loss_sum / len(y_train)
66
+ log['loss_train'].append(loss_train_mean)
67
+ log['acc_train'].append(n_correct_sum / len(y_train))
68
+
69
+ print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}')
70
+
71
+ return log
72
+
73
+ ### Set-up the model: ###
74
+ model = nl.NeuralNetwork([
75
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
76
+ nl.Sigmoid(),
77
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
78
+ nl.Sigmoid(),
79
+ ])
80
+
81
+ # input x1 x2
82
+ X_train = np.array((( 0, 0),
83
+ ( 1, 0),
84
+ ( 0, 1),
85
+ ( 1, 1)))
86
+
87
+ # desired output: logical XOR
88
+ y_train = np.array((1,
89
+ 0,
90
+ 0,
91
+ 1)).reshape((4,1))
92
+
93
+ optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
94
+
95
+ log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
96
+
97
+ plt.plot(log['loss_train'], label='training')
98
+ plt.legend(loc='best')
99
+ plt.xlabel('epoch')
100
+ plt.ylabel('loss')
101
+ plt.grid()
102
+ plt.show()
103
+
104
+ plt.plot(log['acc_train'], label='training')
105
+ plt.legend(loc='best')
106
+ plt.xlabel('epoch')
107
+ plt.ylabel('accuracy')
108
+ plt.grid()
109
+ plt.show()
110
+ ```
111
+
112
+ ## Example 2: 5-layer LeNET CNN, training on MNIST images
113
+
114
+ ```Python
115
+ import numpy as np
116
+ import time
117
+ import matplotlib.pyplot as plt
118
+
119
+ import netlite as nl
120
+
121
+ def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
122
+ log = {}
123
+ log['loss_train'] = []
124
+ log['loss_valid'] = []
125
+ log['acc_train'] = []
126
+ log['acc_valid'] = []
127
+ for epoch in range(n_epochs):
128
+
129
+ ### Training ###
130
+ start_time = time.time()
131
+ loss_sum = 0
132
+ n_correct_sum = 0
133
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
134
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
135
+ loss_sum += loss
136
+ n_correct_sum += metrics['n_correct']
137
+
138
+ end_time = time.time()
139
+ elapsed_time = end_time - start_time
140
+ print(f"runtime: {elapsed_time:.1f} sec")
141
+
142
+ loss_train_mean = loss_sum / len(y_train)
143
+ log['loss_train'].append(loss_train_mean)
144
+ log['acc_train'].append(n_correct_sum / len(y_train))
145
+
146
+ ### Validation ###
147
+ loss_sum = 0
148
+ n_correct_sum = 0
149
+ for x_batch, y_batch in nl.batch_handler(X_valid, y_valid, batchsize=batchsize, shuffle=False):
150
+ loss, metrics = optimizer.step(model, x_batch, y_batch, forward_only=True)
151
+ loss_sum += loss
152
+ n_correct_sum += metrics['n_correct']
153
+
154
+ loss_valid_mean = loss_sum / len(y_valid)
155
+ log['loss_valid'].append(loss_valid_mean)
156
+ log['acc_valid'].append(n_correct_sum / len(y_valid))
157
+ print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, loss_valid {loss_valid_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}, acc_valid {log["acc_valid"][-1]:5.3f}')
158
+
159
+ return log
160
+
161
+
162
+ X_train, y_train = nl.dataloader_mnist.load_train(num_images = 60000)
163
+ X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 10000)
164
+
165
+ # show some numbers
166
+ fig, ax = plt.subplots(1, 6, figsize=(6,1), dpi=100)
167
+ for axis, idx in zip(fig.axes, np.arange(0, 6)):
168
+ axis.imshow(X_train[idx, :, :, :], cmap='gray')
169
+ axis.axis('off')
170
+ plt.show()
171
+
172
+ model = nl.NeuralNetwork([
173
+ nl.ConvolutionalLayer(5, 1, 6),
174
+ nl.ReLU(),
175
+ nl.AvgPoolingLayer(),
176
+ nl.ConvolutionalLayer(5, 6, 16),
177
+ nl.ReLU(),
178
+ nl.AvgPoolingLayer(),
179
+ nl.Flatten(),
180
+ nl.FullyConnectedLayer(n_inputs=400, n_outputs=120),
181
+ nl.ReLU(),
182
+ nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
183
+ nl.ReLU(),
184
+ nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
185
+ nl.Softmax(),
186
+ ])
187
+ loss_func = nl.CrossEntropyLoss()
188
+
189
+ learning_rate = 0.001
190
+ n_epochs = 20 # test acc at ~99% with AvgPooling
191
+ batchsize = 32
192
+
193
+ optimizer = nl.OptimizerADAM(loss_func, learning_rate)
194
+
195
+ log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
196
+
197
+ plt.plot(log['loss_train'], label='training')
198
+ plt.plot(log['loss_valid'], label='validation')
199
+ plt.legend(loc='best')
200
+ plt.xlabel('epoch')
201
+ plt.ylabel('loss')
202
+ plt.tile('Training LeNet on MNIST data')
203
+ plt.grid()
204
+ plt.show()
205
+
206
+ plt.plot(log['acc_train'], label='training')
207
+ plt.plot(log['acc_valid'], label='validation')
208
+ plt.legend(loc='best')
209
+ plt.xlabel('epoch')
210
+ plt.ylabel('accuracy')
211
+ plt.tile('Training LeNet on MNIST data')
212
+ plt.grid()
213
+ plt.show()
214
+ ```
215
+
216
+ ## References
217
+
218
+ [LeNet5](https://github.com/chuanqi305/LeNet5): A plain numpy implementation of LeNet5 with convolutional layers.
219
+ [JB Grabowski](http://www.jbgrabowski.com/notebooks/neural-net/): A Jupyter notebook using ADAM optimization for fully connected layers.
@@ -0,0 +1,199 @@
1
+ # NetLite
2
+
3
+ **A small white-box training framework for neural networks for education.**
4
+
5
+ NetLite provides a light-weight training framework, designed for readability
6
+ for learning the basic principles of neural networks in AI classes.
7
+
8
+ **Performance:**
9
+ - On LeNet, this framework achieves 99% accuracy on the MNIST validation data in just 150 seconds (on my laptop cpu).
10
+ - computation using numpy for most operations
11
+ - just-in-time compilation using numba for convolutions
12
+ - Data-loader allows to limit the number of images used, e.g. to train on just 10% of the MNIST data,
13
+ for even faster training during lab exercises and to get a feeling for over-fitting when not enough data is available.
14
+
15
+ ![Accuracy curve](./images/lenet_mnist_acc_curves.svg)
16
+
17
+ **Fig. 1:** *Accuracy of LeNet5 trained using NetLite's ADAM optimizer.*
18
+
19
+ **Exemplary learning tasks for AI classes using this framework:**
20
+ - Take a given activation function (e.g. ReLU from layers.py) and use it as a template to create your own activation function (e.g. tanh).
21
+ - Implement a robust loss function (e.g. Huber loss) a fit a regression line to noisy data.
22
+ - Use debugger to step through optimization, compare with manual calculations.
23
+ - Understand and compare different optimizers (SGD, Momentum, ADAM).
24
+
25
+ ## Example 1: Training of a 2-layer model as an XOR classifier
26
+
27
+ ```Python
28
+ import numpy as np
29
+ import matplotlib.pyplot as plt
30
+
31
+ import netlite as nl
32
+
33
+ def train(model, optimizer, X_train, y_train, n_epochs=10, batchsize=32):
34
+ log = {}
35
+ log['loss_train'] = []
36
+ log['acc_train'] = []
37
+ for epoch in range(n_epochs):
38
+ loss_sum = 0
39
+ n_correct_sum = 0
40
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
41
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
42
+ loss_sum += loss
43
+ n_correct_sum += metrics['n_correct']
44
+
45
+ loss_train_mean = loss_sum / len(y_train)
46
+ log['loss_train'].append(loss_train_mean)
47
+ log['acc_train'].append(n_correct_sum / len(y_train))
48
+
49
+ print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}')
50
+
51
+ return log
52
+
53
+ ### Set-up the model: ###
54
+ model = nl.NeuralNetwork([
55
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
56
+ nl.Sigmoid(),
57
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
58
+ nl.Sigmoid(),
59
+ ])
60
+
61
+ # input x1 x2
62
+ X_train = np.array((( 0, 0),
63
+ ( 1, 0),
64
+ ( 0, 1),
65
+ ( 1, 1)))
66
+
67
+ # desired output: logical XOR
68
+ y_train = np.array((1,
69
+ 0,
70
+ 0,
71
+ 1)).reshape((4,1))
72
+
73
+ optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
74
+
75
+ log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
76
+
77
+ plt.plot(log['loss_train'], label='training')
78
+ plt.legend(loc='best')
79
+ plt.xlabel('epoch')
80
+ plt.ylabel('loss')
81
+ plt.grid()
82
+ plt.show()
83
+
84
+ plt.plot(log['acc_train'], label='training')
85
+ plt.legend(loc='best')
86
+ plt.xlabel('epoch')
87
+ plt.ylabel('accuracy')
88
+ plt.grid()
89
+ plt.show()
90
+ ```
91
+
92
+ ## Example 2: 5-layer LeNET CNN, training on MNIST images
93
+
94
+ ```Python
95
+ import numpy as np
96
+ import time
97
+ import matplotlib.pyplot as plt
98
+
99
+ import netlite as nl
100
+
101
+ def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
102
+ log = {}
103
+ log['loss_train'] = []
104
+ log['loss_valid'] = []
105
+ log['acc_train'] = []
106
+ log['acc_valid'] = []
107
+ for epoch in range(n_epochs):
108
+
109
+ ### Training ###
110
+ start_time = time.time()
111
+ loss_sum = 0
112
+ n_correct_sum = 0
113
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
114
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
115
+ loss_sum += loss
116
+ n_correct_sum += metrics['n_correct']
117
+
118
+ end_time = time.time()
119
+ elapsed_time = end_time - start_time
120
+ print(f"runtime: {elapsed_time:.1f} sec")
121
+
122
+ loss_train_mean = loss_sum / len(y_train)
123
+ log['loss_train'].append(loss_train_mean)
124
+ log['acc_train'].append(n_correct_sum / len(y_train))
125
+
126
+ ### Validation ###
127
+ loss_sum = 0
128
+ n_correct_sum = 0
129
+ for x_batch, y_batch in nl.batch_handler(X_valid, y_valid, batchsize=batchsize, shuffle=False):
130
+ loss, metrics = optimizer.step(model, x_batch, y_batch, forward_only=True)
131
+ loss_sum += loss
132
+ n_correct_sum += metrics['n_correct']
133
+
134
+ loss_valid_mean = loss_sum / len(y_valid)
135
+ log['loss_valid'].append(loss_valid_mean)
136
+ log['acc_valid'].append(n_correct_sum / len(y_valid))
137
+ print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, loss_valid {loss_valid_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}, acc_valid {log["acc_valid"][-1]:5.3f}')
138
+
139
+ return log
140
+
141
+
142
+ X_train, y_train = nl.dataloader_mnist.load_train(num_images = 60000)
143
+ X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 10000)
144
+
145
+ # show some numbers
146
+ fig, ax = plt.subplots(1, 6, figsize=(6,1), dpi=100)
147
+ for axis, idx in zip(fig.axes, np.arange(0, 6)):
148
+ axis.imshow(X_train[idx, :, :, :], cmap='gray')
149
+ axis.axis('off')
150
+ plt.show()
151
+
152
+ model = nl.NeuralNetwork([
153
+ nl.ConvolutionalLayer(5, 1, 6),
154
+ nl.ReLU(),
155
+ nl.AvgPoolingLayer(),
156
+ nl.ConvolutionalLayer(5, 6, 16),
157
+ nl.ReLU(),
158
+ nl.AvgPoolingLayer(),
159
+ nl.Flatten(),
160
+ nl.FullyConnectedLayer(n_inputs=400, n_outputs=120),
161
+ nl.ReLU(),
162
+ nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
163
+ nl.ReLU(),
164
+ nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
165
+ nl.Softmax(),
166
+ ])
167
+ loss_func = nl.CrossEntropyLoss()
168
+
169
+ learning_rate = 0.001
170
+ n_epochs = 20 # test acc at ~99% with AvgPooling
171
+ batchsize = 32
172
+
173
+ optimizer = nl.OptimizerADAM(loss_func, learning_rate)
174
+
175
+ log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
176
+
177
+ plt.plot(log['loss_train'], label='training')
178
+ plt.plot(log['loss_valid'], label='validation')
179
+ plt.legend(loc='best')
180
+ plt.xlabel('epoch')
181
+ plt.ylabel('loss')
182
+ plt.tile('Training LeNet on MNIST data')
183
+ plt.grid()
184
+ plt.show()
185
+
186
+ plt.plot(log['acc_train'], label='training')
187
+ plt.plot(log['acc_valid'], label='validation')
188
+ plt.legend(loc='best')
189
+ plt.xlabel('epoch')
190
+ plt.ylabel('accuracy')
191
+ plt.tile('Training LeNet on MNIST data')
192
+ plt.grid()
193
+ plt.show()
194
+ ```
195
+
196
+ ## References
197
+
198
+ [LeNet5](https://github.com/chuanqi305/LeNet5): A plain numpy implementation of LeNet5 with convolutional layers.
199
+ [JB Grabowski](http://www.jbgrabowski.com/notebooks/neural-net/): A Jupyter notebook using ADAM optimization for fully connected layers.