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