netlite 0.0.4__tar.gz → 0.0.6__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.
- {netlite-0.0.4 → netlite-0.0.6}/LICENSE +20 -20
- {netlite-0.0.4 → netlite-0.0.6}/PKG-INFO +1 -1
- {netlite-0.0.4 → netlite-0.0.6}/README.md +199 -199
- {netlite-0.0.4 → netlite-0.0.6}/examples/netlite_example_fit_regression_line.py +65 -65
- {netlite-0.0.4 → netlite-0.0.6}/examples/netlite_example_lenet_cifar10.py +109 -109
- {netlite-0.0.4 → netlite-0.0.6}/examples/netlite_example_lenet_mnist.py +108 -108
- {netlite-0.0.4 → netlite-0.0.6}/examples/netlite_example_xor_classifier.py +68 -68
- netlite-0.0.6/images/logo_netlite.png +0 -0
- {netlite-0.0.4 → netlite-0.0.6}/package_build.sh +3 -3
- {netlite-0.0.4 → netlite-0.0.6}/pyproject.toml +28 -28
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/__init__.py +19 -22
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/dataloader_cifar10.py +103 -103
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/dataloader_mnist.py +99 -99
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/layers.py +285 -283
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/loss_functions.py +91 -91
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/neural_network.py +62 -47
- {netlite-0.0.4 → netlite-0.0.6}/src/netlite/optimizer.py +140 -139
- {netlite-0.0.4 → netlite-0.0.6}/tests/netlite_test.py +169 -169
- {netlite-0.0.4 → netlite-0.0.6}/tests/netlite_test_convolution.py +108 -108
- {netlite-0.0.4 → netlite-0.0.6}/.gitignore +0 -0
- {netlite-0.0.4 → netlite-0.0.6}/images/lenet_mnist_acc_curves.svg +0 -0
- {netlite-0.0.4 → netlite-0.0.6}/package_upload.sh +0 -0
- {netlite-0.0.4 → netlite-0.0.6}/requirements.txt +0 -0
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
Copyright (c) 2025 Hanno Homann
|
|
2
|
-
|
|
3
|
-
--- MIT License ---
|
|
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
|
|
1
|
+
Copyright (c) 2025 Hanno Homann
|
|
2
|
+
|
|
3
|
+
--- MIT License ---
|
|
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
21
|
SOFTWARE.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: netlite
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.6
|
|
4
4
|
Summary: A small white-box training framework for neural networks for education.
|
|
5
5
|
Project-URL: Homepage, https://github.com/haho12/netlite
|
|
6
6
|
Project-URL: Issues, https://github.com/haho12/netlite/issues
|
|
@@ -1,200 +1,200 @@
|
|
|
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 within a few epochs, taking less than 30 seconds per epoch which is roughly on par with PyTorch (on my laptop cpu).
|
|
10
|
-
- Optimizations:
|
|
11
|
-
- computation using numpy for most operations
|
|
12
|
-
- just-in-time compilation using numba for convolutions
|
|
13
|
-
- Data-loader allows to limit the number of images used, e.g. to train on just 10% of the MNIST data,
|
|
14
|
-
for even faster training during lab exercises and to get a feeling for over-fitting when not enough data is available.
|
|
15
|
-
|
|
16
|
-

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

|
|
17
|
+
|
|
18
|
+
**Fig. 1:** *Accuracy of LeNet5 trained using NetLite's ADAM optimizer.*
|
|
19
|
+
|
|
20
|
+
**Exemplary learning tasks for AI classes using this framework:**
|
|
21
|
+
- 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).
|
|
22
|
+
- Implement a robust loss function (e.g. Huber loss) a fit a regression line to noisy data.
|
|
23
|
+
- Use debugger to step through optimization, compare with manual calculations.
|
|
24
|
+
- Understand and compare different optimizers (SGD, Momentum, ADAM).
|
|
25
|
+
|
|
26
|
+
## Example 1: Training of a 2-layer model as an XOR classifier
|
|
27
|
+
|
|
28
|
+
```Python
|
|
29
|
+
import numpy as np
|
|
30
|
+
import matplotlib.pyplot as plt
|
|
31
|
+
|
|
32
|
+
import netlite as nl
|
|
33
|
+
|
|
34
|
+
def train(model, optimizer, X_train, y_train, n_epochs=10, batchsize=32):
|
|
35
|
+
log = {}
|
|
36
|
+
log['loss_train'] = []
|
|
37
|
+
log['acc_train'] = []
|
|
38
|
+
for epoch in range(n_epochs):
|
|
39
|
+
loss_sum = 0
|
|
40
|
+
n_correct_sum = 0
|
|
41
|
+
for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
|
|
42
|
+
loss, metrics = optimizer.step(model, x_batch, y_batch)
|
|
43
|
+
loss_sum += loss
|
|
44
|
+
n_correct_sum += metrics['n_correct']
|
|
45
|
+
|
|
46
|
+
loss_train_mean = loss_sum / len(y_train)
|
|
47
|
+
log['loss_train'].append(loss_train_mean)
|
|
48
|
+
log['acc_train'].append(n_correct_sum / len(y_train))
|
|
49
|
+
|
|
50
|
+
print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}')
|
|
51
|
+
|
|
52
|
+
return log
|
|
53
|
+
|
|
54
|
+
### Set-up the model: ###
|
|
55
|
+
model = nl.NeuralNetwork([
|
|
56
|
+
nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
|
|
57
|
+
nl.Sigmoid(),
|
|
58
|
+
nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
|
|
59
|
+
nl.Sigmoid(),
|
|
60
|
+
])
|
|
61
|
+
|
|
62
|
+
# input x1 x2
|
|
63
|
+
X_train = np.array((( 0, 0),
|
|
64
|
+
( 1, 0),
|
|
65
|
+
( 0, 1),
|
|
66
|
+
( 1, 1)))
|
|
67
|
+
|
|
68
|
+
# desired output: logical XOR
|
|
69
|
+
y_train = np.array((1,
|
|
70
|
+
0,
|
|
71
|
+
0,
|
|
72
|
+
1)).reshape((4,1))
|
|
73
|
+
|
|
74
|
+
optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
|
|
75
|
+
|
|
76
|
+
log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
|
|
77
|
+
|
|
78
|
+
plt.plot(log['loss_train'], label='training')
|
|
79
|
+
plt.legend(loc='best')
|
|
80
|
+
plt.xlabel('epoch')
|
|
81
|
+
plt.ylabel('loss')
|
|
82
|
+
plt.grid()
|
|
83
|
+
plt.show()
|
|
84
|
+
|
|
85
|
+
plt.plot(log['acc_train'], label='training')
|
|
86
|
+
plt.legend(loc='best')
|
|
87
|
+
plt.xlabel('epoch')
|
|
88
|
+
plt.ylabel('accuracy')
|
|
89
|
+
plt.grid()
|
|
90
|
+
plt.show()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Example 2: 5-layer LeNET CNN, training on MNIST images
|
|
94
|
+
|
|
95
|
+
```Python
|
|
96
|
+
import numpy as np
|
|
97
|
+
import time
|
|
98
|
+
import matplotlib.pyplot as plt
|
|
99
|
+
|
|
100
|
+
import netlite as nl
|
|
101
|
+
|
|
102
|
+
def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
|
|
103
|
+
log = {}
|
|
104
|
+
log['loss_train'] = []
|
|
105
|
+
log['loss_valid'] = []
|
|
106
|
+
log['acc_train'] = []
|
|
107
|
+
log['acc_valid'] = []
|
|
108
|
+
for epoch in range(n_epochs):
|
|
109
|
+
|
|
110
|
+
### Training ###
|
|
111
|
+
start_time = time.time()
|
|
112
|
+
loss_sum = 0
|
|
113
|
+
n_correct_sum = 0
|
|
114
|
+
for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
|
|
115
|
+
loss, metrics = optimizer.step(model, x_batch, y_batch)
|
|
116
|
+
loss_sum += loss
|
|
117
|
+
n_correct_sum += metrics['n_correct']
|
|
118
|
+
|
|
119
|
+
end_time = time.time()
|
|
120
|
+
elapsed_time = end_time - start_time
|
|
121
|
+
print(f"runtime: {elapsed_time:.1f} sec")
|
|
122
|
+
|
|
123
|
+
loss_train_mean = loss_sum / len(y_train)
|
|
124
|
+
log['loss_train'].append(loss_train_mean)
|
|
125
|
+
log['acc_train'].append(n_correct_sum / len(y_train))
|
|
126
|
+
|
|
127
|
+
### Validation ###
|
|
128
|
+
loss_sum = 0
|
|
129
|
+
n_correct_sum = 0
|
|
130
|
+
for x_batch, y_batch in nl.batch_handler(X_valid, y_valid, batchsize=batchsize, shuffle=False):
|
|
131
|
+
loss, metrics = optimizer.step(model, x_batch, y_batch, forward_only=True)
|
|
132
|
+
loss_sum += loss
|
|
133
|
+
n_correct_sum += metrics['n_correct']
|
|
134
|
+
|
|
135
|
+
loss_valid_mean = loss_sum / len(y_valid)
|
|
136
|
+
log['loss_valid'].append(loss_valid_mean)
|
|
137
|
+
log['acc_valid'].append(n_correct_sum / len(y_valid))
|
|
138
|
+
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}')
|
|
139
|
+
|
|
140
|
+
return log
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
X_train, y_train = nl.dataloader_mnist.load_train(num_images = 60000)
|
|
144
|
+
X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 10000)
|
|
145
|
+
|
|
146
|
+
# show some numbers
|
|
147
|
+
fig, ax = plt.subplots(1, 6, figsize=(6,1), dpi=100)
|
|
148
|
+
for axis, idx in zip(fig.axes, np.arange(0, 6)):
|
|
149
|
+
axis.imshow(X_train[idx, :, :, :], cmap='gray')
|
|
150
|
+
axis.axis('off')
|
|
151
|
+
plt.show()
|
|
152
|
+
|
|
153
|
+
model = nl.NeuralNetwork([
|
|
154
|
+
nl.ConvolutionalLayer(5, 1, 6),
|
|
155
|
+
nl.ReLU(),
|
|
156
|
+
nl.AvgPoolingLayer(),
|
|
157
|
+
nl.ConvolutionalLayer(5, 6, 16),
|
|
158
|
+
nl.ReLU(),
|
|
159
|
+
nl.AvgPoolingLayer(),
|
|
160
|
+
nl.Flatten(),
|
|
161
|
+
nl.FullyConnectedLayer(n_inputs=400, n_outputs=120),
|
|
162
|
+
nl.ReLU(),
|
|
163
|
+
nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
|
|
164
|
+
nl.ReLU(),
|
|
165
|
+
nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
|
|
166
|
+
nl.Softmax(),
|
|
167
|
+
])
|
|
168
|
+
loss_func = nl.CrossEntropyLoss()
|
|
169
|
+
|
|
170
|
+
learning_rate = 0.001
|
|
171
|
+
n_epochs = 20 # test acc at ~99% with AvgPooling
|
|
172
|
+
batchsize = 32
|
|
173
|
+
|
|
174
|
+
optimizer = nl.OptimizerADAM(loss_func, learning_rate)
|
|
175
|
+
|
|
176
|
+
log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
|
|
177
|
+
|
|
178
|
+
plt.plot(log['loss_train'], label='training')
|
|
179
|
+
plt.plot(log['loss_valid'], label='validation')
|
|
180
|
+
plt.legend(loc='best')
|
|
181
|
+
plt.xlabel('epoch')
|
|
182
|
+
plt.ylabel('loss')
|
|
183
|
+
plt.tile('Training LeNet on MNIST data')
|
|
184
|
+
plt.grid()
|
|
185
|
+
plt.show()
|
|
186
|
+
|
|
187
|
+
plt.plot(log['acc_train'], label='training')
|
|
188
|
+
plt.plot(log['acc_valid'], label='validation')
|
|
189
|
+
plt.legend(loc='best')
|
|
190
|
+
plt.xlabel('epoch')
|
|
191
|
+
plt.ylabel('accuracy')
|
|
192
|
+
plt.tile('Training LeNet on MNIST data')
|
|
193
|
+
plt.grid()
|
|
194
|
+
plt.show()
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## References
|
|
198
|
+
|
|
199
|
+
[LeNet5](https://github.com/chuanqi305/LeNet5): A plain numpy implementation of LeNet5 with convolutional layers.
|
|
200
200
|
[JB Grabowski](http://www.jbgrabowski.com/notebooks/neural-net/): A Jupyter notebook using ADAM optimization for fully connected layers.
|
|
@@ -1,65 +1,65 @@
|
|
|
1
|
-
import numpy as np
|
|
2
|
-
import matplotlib.pyplot as plt
|
|
3
|
-
import sys
|
|
4
|
-
import os
|
|
5
|
-
|
|
6
|
-
# add parent folder with netlite source to path
|
|
7
|
-
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
|
|
8
|
-
sys.path.insert(0, parent_dir)
|
|
9
|
-
import netlite as nl
|
|
10
|
-
|
|
11
|
-
def training_loop(model, optimizer, X_train, y_train, n_epochs=2000):
|
|
12
|
-
log = {}
|
|
13
|
-
log['loss_train'] = []
|
|
14
|
-
for epoch in range(n_epochs):
|
|
15
|
-
loss_sum, _ = optimizer.step(model, X_train, y_train)
|
|
16
|
-
|
|
17
|
-
loss_train_mean = loss_sum / len(y_train)
|
|
18
|
-
log['loss_train'].append(loss_train_mean)
|
|
19
|
-
|
|
20
|
-
print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}')
|
|
21
|
-
|
|
22
|
-
return log
|
|
23
|
-
|
|
24
|
-
# create some random data points
|
|
25
|
-
x_train = np.arange(0, 20).reshape((-1,1))
|
|
26
|
-
#y_train = (x_train * m_gt + b_gt) + np.random.rand(num_points)*10
|
|
27
|
-
y_train = np.array([ -1.1773, 2.1500, -0.1714, 8.5931, 5.9045,
|
|
28
|
-
11.0090, 10.5657, 18.9364, 23.4077, 18.3319,
|
|
29
|
-
29.3460, 28.9358, 34.6940, 34.6772, 39.4109,
|
|
30
|
-
39.2940, 46.8544, 46.7390, 46.6658, 53.2745]).reshape((-1,1))
|
|
31
|
-
|
|
32
|
-
y_train[3:5] -= 40 # outliers
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
# A simple linear model: y = w*x + b
|
|
36
|
-
model1 = nl.NeuralNetwork([
|
|
37
|
-
nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
|
|
38
|
-
])
|
|
39
|
-
optimizer1 = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=0.0001)
|
|
40
|
-
log1 = training_loop(model1, optimizer1, x_train, y_train)
|
|
41
|
-
|
|
42
|
-
model2 = nl.NeuralNetwork([
|
|
43
|
-
nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
|
|
44
|
-
])
|
|
45
|
-
optimizer2 = nl.OptimizerSGD(loss_func=nl.HuberLoss(2.0), learning_rate=0.0001)
|
|
46
|
-
log2 = training_loop(model2, optimizer2, x_train, y_train)
|
|
47
|
-
|
|
48
|
-
model1_out = model1.forward(x_train)
|
|
49
|
-
model2_out = model2.forward(x_train)
|
|
50
|
-
plt.scatter(x_train, y_train, color='red', label='data')
|
|
51
|
-
plt.plot(x_train, model1_out, color='blue', label='MSE regression fit')
|
|
52
|
-
plt.plot(x_train, model2_out, color='green', label='Huber regression fit')
|
|
53
|
-
plt.legend(loc='best')
|
|
54
|
-
plt.xlabel('x')
|
|
55
|
-
plt.ylabel('y')
|
|
56
|
-
plt.grid()
|
|
57
|
-
plt.show()
|
|
58
|
-
|
|
59
|
-
plt.plot(log1['loss_train'] / log1['loss_train'][0], label='MSE loss')
|
|
60
|
-
plt.plot(log2['loss_train'] / log2['loss_train'][0], label='Huber loss')
|
|
61
|
-
plt.legend(loc='best')
|
|
62
|
-
plt.xlabel('epoch')
|
|
63
|
-
plt.ylabel('loss')
|
|
64
|
-
plt.grid()
|
|
65
|
-
plt.show()
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
import sys
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
# add parent folder with netlite source to path
|
|
7
|
+
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
|
|
8
|
+
sys.path.insert(0, parent_dir)
|
|
9
|
+
import netlite as nl
|
|
10
|
+
|
|
11
|
+
def training_loop(model, optimizer, X_train, y_train, n_epochs=2000):
|
|
12
|
+
log = {}
|
|
13
|
+
log['loss_train'] = []
|
|
14
|
+
for epoch in range(n_epochs):
|
|
15
|
+
loss_sum, _ = optimizer.step(model, X_train, y_train)
|
|
16
|
+
|
|
17
|
+
loss_train_mean = loss_sum / len(y_train)
|
|
18
|
+
log['loss_train'].append(loss_train_mean)
|
|
19
|
+
|
|
20
|
+
print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}')
|
|
21
|
+
|
|
22
|
+
return log
|
|
23
|
+
|
|
24
|
+
# create some random data points
|
|
25
|
+
x_train = np.arange(0, 20).reshape((-1,1))
|
|
26
|
+
#y_train = (x_train * m_gt + b_gt) + np.random.rand(num_points)*10
|
|
27
|
+
y_train = np.array([ -1.1773, 2.1500, -0.1714, 8.5931, 5.9045,
|
|
28
|
+
11.0090, 10.5657, 18.9364, 23.4077, 18.3319,
|
|
29
|
+
29.3460, 28.9358, 34.6940, 34.6772, 39.4109,
|
|
30
|
+
39.2940, 46.8544, 46.7390, 46.6658, 53.2745]).reshape((-1,1))
|
|
31
|
+
|
|
32
|
+
y_train[3:5] -= 40 # outliers
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# A simple linear model: y = w*x + b
|
|
36
|
+
model1 = nl.NeuralNetwork([
|
|
37
|
+
nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
|
|
38
|
+
])
|
|
39
|
+
optimizer1 = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=0.0001)
|
|
40
|
+
log1 = training_loop(model1, optimizer1, x_train, y_train)
|
|
41
|
+
|
|
42
|
+
model2 = nl.NeuralNetwork([
|
|
43
|
+
nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
|
|
44
|
+
])
|
|
45
|
+
optimizer2 = nl.OptimizerSGD(loss_func=nl.HuberLoss(2.0), learning_rate=0.0001)
|
|
46
|
+
log2 = training_loop(model2, optimizer2, x_train, y_train)
|
|
47
|
+
|
|
48
|
+
model1_out = model1.forward(x_train)
|
|
49
|
+
model2_out = model2.forward(x_train)
|
|
50
|
+
plt.scatter(x_train, y_train, color='red', label='data')
|
|
51
|
+
plt.plot(x_train, model1_out, color='blue', label='MSE regression fit')
|
|
52
|
+
plt.plot(x_train, model2_out, color='green', label='Huber regression fit')
|
|
53
|
+
plt.legend(loc='best')
|
|
54
|
+
plt.xlabel('x')
|
|
55
|
+
plt.ylabel('y')
|
|
56
|
+
plt.grid()
|
|
57
|
+
plt.show()
|
|
58
|
+
|
|
59
|
+
plt.plot(log1['loss_train'] / log1['loss_train'][0], label='MSE loss')
|
|
60
|
+
plt.plot(log2['loss_train'] / log2['loss_train'][0], label='Huber loss')
|
|
61
|
+
plt.legend(loc='best')
|
|
62
|
+
plt.xlabel('epoch')
|
|
63
|
+
plt.ylabel('loss')
|
|
64
|
+
plt.grid()
|
|
65
|
+
plt.show()
|