netlite 0.0.1__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.
netlite/__init__.py ADDED
File without changes
@@ -0,0 +1,100 @@
1
+ # reference: https://www.cs.toronto.edu/~kriz/
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+
5
+ import os.path
6
+ import tarfile
7
+ import urllib.request
8
+ import pickle
9
+
10
+ def load_train(input_path = 'cifar10_raw', num_images = 50000):
11
+ images = np.zeros((num_images, 32, 32, 3), dtype=np.float32)
12
+ labels = np.zeros(num_images, dtype=np.int32)
13
+ num_batches = int(np.ceil(num_images / 10000))
14
+ for i in range(num_batches):
15
+ images_file = 'data_batch_' + str(i+1)
16
+ if i == num_batches - 1:
17
+ num_images_i = num_images - i * 10000
18
+ else:
19
+ num_images_i = 10000
20
+ images_i, labels_i = load(input_path, images_file, num_images_i)
21
+
22
+ images[i*10000:(i+1)*10000,:,:,:] = images_i
23
+ labels[i*10000:(i+1)*10000] = labels_i
24
+
25
+ return images, labels
26
+
27
+ def load_valid(input_path = 'cifar10_raw', num_images = 10000):
28
+ images_file = 'test_batch'
29
+ return load(input_path, images_file, num_images)
30
+
31
+ def download(download_dir, filename):
32
+ if not os.path.isdir(download_dir):
33
+ os.mkdir(download_dir)
34
+ url = "https://www.cs.toronto.edu/~kriz/" + filename
35
+ targetfile = os.path.join(download_dir, filename)
36
+ print("Downloading: " + filename + " ...")
37
+ urllib.request.urlretrieve(url, targetfile)
38
+
39
+ def extract(download_dir, filename):
40
+ targetfile = os.path.join(download_dir, filename)
41
+ tar_file = tarfile.open(targetfile)
42
+ tar_file.extractall(download_dir)
43
+ tar_file.close()
44
+
45
+ def load(input_path, images_file, num_images_max):
46
+ gz_filename = 'cifar-10-python.tar.gz'
47
+ gz_path = os.path.join(input_path, gz_filename)
48
+ raw_path = os.path.join(input_path, 'cifar-10-batches-py', images_file)
49
+
50
+ if not os.path.isfile(gz_path):
51
+ download(input_path, gz_filename)
52
+ if not os.path.isfile(raw_path):
53
+ extract(input_path, gz_filename)
54
+
55
+ with open(raw_path, 'rb') as fo:
56
+ dict = pickle.load(fo, encoding='bytes')
57
+
58
+
59
+ data = dict[b'data']
60
+ labels = np.array(dict[b'labels'])
61
+ num_images = len(labels) # Todo: currently only loading batch 1 of 5
62
+ num_images_max = min(num_images, num_images_max)
63
+
64
+ images = np.zeros((num_images_max, 32, 32, 3), dtype=np.float32)
65
+ for i in range(num_images_max):
66
+ data_np = data[i].reshape(3,32,32) / 255.
67
+
68
+ images[i,:,:,0] = data_np[0,:,:]
69
+ images[i,:,:,1] = data_np[1,:,:]
70
+ images[i,:,:,2] = data_np[2,:,:]
71
+
72
+ return images, labels[:num_images_max]
73
+
74
+ def show_images(images, labels):
75
+ cols = 5
76
+ rows = 2
77
+
78
+ plt.figure(figsize=(10,7))
79
+
80
+ class_names = ('plane', 'car', 'bird', 'cat', 'deer',
81
+ 'dog', 'frog', 'horse', 'ship', 'truck')
82
+ for i in range(cols*rows):
83
+ plt.subplot(rows, cols, i+1)
84
+ plt.imshow(images[i,:,:,:])
85
+ plt.title("label: " + str(labels[i]) + " (" + class_names[labels[i]] + ")")
86
+ plt.axis('off')
87
+
88
+ if __name__ == '__main__':
89
+ images, labels = load_train()
90
+ show_images(images, labels)
91
+
92
+ #count = 0
93
+ #for i in range(images.shape[0]):
94
+ # if labels[i] == 7: # horse
95
+ # plt.imsave("cifar10_horses\\horse_" + str(count) + '.png', images[i,:,:,:])
96
+ # count += 1
97
+ # if count >= 10:
98
+ # break
99
+
100
+
@@ -0,0 +1,95 @@
1
+ # reference: http://yann.lecun.com/exdb/mnist/
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+
5
+ import os.path
6
+ import gzip
7
+ import urllib.request
8
+
9
+ def load_train(input_path = 'mnist_raw', num_images = 60000):
10
+ images_file = 'train-images-idx3-ubyte.gz'
11
+ labels_file = 'train-labels-idx1-ubyte.gz'
12
+ return load(input_path, images_file, labels_file, num_images)
13
+
14
+ def load_valid(input_path = 'mnist_raw', num_images = 10000):
15
+ images_file = 't10k-images-idx3-ubyte.gz'
16
+ labels_file = 't10k-labels-idx1-ubyte.gz'
17
+ return load(input_path, images_file, labels_file, num_images)
18
+
19
+ def download(download_dir, filename):
20
+ if not os.path.isdir(download_dir):
21
+ os.mkdir(download_dir)
22
+ urls = ["http://yann.lecun.com/exdb/mnist/",
23
+ "https://huggingface.co/datasets/dmitva/the-mnist-database/blob/main/",
24
+ "https://wuecampus.uni-wuerzburg.de/moodle/pluginfile.php/4698779/mod_folder/content/0/",
25
+ "https://huggingface.co/spaces/chrisjay/mnist-adversarial/raw/603879aac618aca69749a8a9172daec23a9dd2c4/files/MNIST/raw/",
26
+ ]
27
+ target_file = os.path.join(download_dir, filename)
28
+ print("Downloading '" + filename + "' : ")
29
+ for url in urls:
30
+ source_file = url + filename
31
+ try:
32
+ #print(f"Attempting to download: {source_file}")
33
+ urllib.request.urlretrieve(source_file, target_file)
34
+ #print(f"Successfully downloaded: {target_file}")
35
+ print('+')
36
+ break
37
+ except Exception as e:
38
+ #print(f"Failed to download {source_file}: {e}")
39
+ print('-')
40
+ continue
41
+
42
+ def load(input_path, images_file, labels_file, num_images_max):
43
+ images_path = os.path.join(input_path, images_file)
44
+ labels_path = os.path.join(input_path, labels_file)
45
+ if not os.path.isfile(images_path):
46
+ download(input_path, images_file)
47
+ if not os.path.isfile(labels_path):
48
+ download(input_path, labels_file)
49
+
50
+ images_byte = gzip.open(images_path, 'r')
51
+ labels_byte = gzip.open(labels_path, 'r')
52
+
53
+ # read images
54
+ magic_num = int.from_bytes(images_byte.read(4), byteorder='big')
55
+ num_images = int.from_bytes(images_byte.read(4), byteorder='big')
56
+ img_height = int.from_bytes(images_byte.read(4), byteorder='big')
57
+ img_width = int.from_bytes(images_byte.read(4), byteorder='big')
58
+ assert(magic_num == 2051)
59
+ assert(img_height == 28)
60
+ assert(img_width == 28)
61
+
62
+ num_images_max = min(num_images, num_images_max)
63
+
64
+ images = np.zeros((num_images_max, 32, 32, 1), dtype=np.float32)
65
+ for i in range(num_images_max):
66
+ data_raw = images_byte.read(img_height * img_width)
67
+ data_np = np.frombuffer(data_raw, dtype=np.uint8)
68
+ images[i,2:-2,2:-2,0] = data_np.reshape(28,28) / 255.
69
+
70
+ # read labels
71
+ magic_num = int.from_bytes(labels_byte.read(4), byteorder='big')
72
+ num_labels = int.from_bytes(labels_byte.read(4), byteorder='big')
73
+ assert(magic_num == 2049)
74
+ assert(num_labels == num_images)
75
+
76
+ buf = labels_byte.read(num_images_max)
77
+ labels = np.frombuffer(buf, dtype=np.uint8)
78
+
79
+ return images, labels
80
+
81
+ def show_images(images, labels):
82
+ cols = 5
83
+ rows = 2
84
+
85
+ plt.figure(figsize=(10,7))
86
+
87
+ for i in range(cols*rows):
88
+ plt.subplot(rows, cols, i+1)
89
+ plt.imshow(images[i,:,:,0], cmap="gray")
90
+ plt.title("label: " + str(labels[i]))
91
+ plt.axis('off')
92
+
93
+ if __name__ == '__main__':
94
+ images, labels = load_train()
95
+ show_images(images, labels)
netlite/netlite.py ADDED
@@ -0,0 +1,524 @@
1
+ # Copyright (c): Hanno Homann, 2024-'25
2
+
3
+ import numpy as np
4
+ import numba
5
+ import time
6
+ import matplotlib.pyplot as plt
7
+ from abc import ABC, abstractmethod
8
+
9
+ class Layer(ABC):
10
+ '''Interface for neural network layers'''
11
+
12
+ @abstractmethod
13
+ def forward(self, X):
14
+ '''Propagate input forward through the layer.'''
15
+ pass
16
+
17
+ @abstractmethod
18
+ def backward(self, grad_backward):
19
+ '''Propagate gradient backward through the layer.'''
20
+ pass
21
+
22
+ def get_weights(self):
23
+ '''Return a dictionary of named trainable parameters.
24
+ The parameters are returned by reference to a numpy array
25
+ to be updated by the optimizer.'''
26
+ return {} # default: no trainable parameters
27
+
28
+ def get_gradients(self):
29
+ '''Return a dictionary of named gradients for each trainable parameter.'''
30
+ return {} # default: no trainable parameters
31
+
32
+ class ReLU(Layer):
33
+ '''Rectified linear unit activation'''
34
+ def forward(self, X):
35
+ self.X = X
36
+ return np.maximum(X, 0)
37
+
38
+ def backward(self, grad_backward):
39
+ relu_gradient = self.X > 0
40
+ return grad_backward * relu_gradient
41
+
42
+ class LeakyReLU(Layer):
43
+ '''Rectified linear unit activation with a leak-factor'''
44
+ leak_factor = np.float32(0.1)
45
+
46
+ def forward(self, X):
47
+ self.X = X
48
+ return ((X>0) + self.leak_factor*(X<0)) * X
49
+
50
+ def backward(self, grad_backward):
51
+ return ((self.X>0) + self.leak_factor*(self.X<0)) * grad_backward
52
+
53
+ class Sigmoid(Layer):
54
+ '''Sigmoid activation'''
55
+ def forward(self, X):
56
+ self.X = X
57
+ self.Y = 1/(1 + np.exp(-X))
58
+ return self.Y
59
+
60
+ def backward(self, grad_backward):
61
+ df = self.Y * (1 - self.Y)
62
+ return df * grad_backward
63
+
64
+ class Softmax(Layer):
65
+ '''Softmax classifier'''
66
+ def forward(self, X):
67
+ softmax = np.exp(X) / np.exp(X).sum(axis=-1,keepdims=True)
68
+ return softmax
69
+
70
+ def backward(self, grad_backward):
71
+ raise SystemExit("Error: Softmax backpropagation is not efficient and " +
72
+ "numerically less stable. " +
73
+ "Use CrossEntropyLoss with logits instead!")
74
+
75
+ class Flatten(Layer):
76
+ '''Flatten an input tensor to a vector'''
77
+ def forward(self, X):
78
+ self.X_shape = X.shape
79
+ return X.copy().reshape(X.shape[0], -1)
80
+
81
+ def backward(self, grad_backward):
82
+ return grad_backward.reshape(self.X_shape)
83
+
84
+ class FullyConnectedLayer(Layer):
85
+ '''Fully connected aka Dense layer'''
86
+ def __init__(self, n_inputs, n_outputs):
87
+ # n_inputs: number of input channels
88
+ # n_outputs: number of output channels
89
+
90
+ self.n_inputs = n_inputs
91
+ self.n_outputs = n_outputs
92
+ self.initialize_weights()
93
+
94
+ # storage for adam momentums
95
+ self.m = {}
96
+ self.v = {}
97
+
98
+ def initialize_weights(self):
99
+ stddev = np.sqrt(2.0 / (self.n_inputs)) # msra
100
+ self.weights = np.random.normal(0.0, stddev, size=(self.n_inputs, self.n_outputs)).astype('f')
101
+ self.bias = np.zeros((1, self.n_outputs), dtype='f')
102
+
103
+ def forward(self, X):
104
+ self.X = X
105
+ return X @ self.weights + self.bias
106
+
107
+ def backward(self, grad_backward):
108
+ # store gradients of weights for update
109
+ self.grad_weights = self.X.T @ grad_backward
110
+ self.grad_bias = np.sum(grad_backward, axis=0, keepdims=True)
111
+
112
+ # back-propagate gradients
113
+ grad_input = grad_backward @ self.weights.T # chain-rule
114
+ return grad_input
115
+
116
+ def get_weights(self):
117
+ # return a dictionary of named parameters
118
+ return {'weights' : self.weights, 'bias': self.bias}
119
+
120
+ def get_gradients(self):
121
+ # return a dictionary of named gradients
122
+ return {'weights' : self.grad_weights, 'bias': self.grad_bias}
123
+
124
+ class ConvolutionalLayer(Layer):
125
+ def __init__(self, kernel_width, inc, outc):
126
+ self.kernel = kernel_width
127
+ k = kernel_width
128
+ self.inc = inc
129
+ self.outc = outc
130
+ stddev = np.sqrt(2.0 / (k**2 * inc)) # msra
131
+ self.weights = np.random.normal(0.0, stddev, size=(k, k, inc, outc)).astype('f')
132
+ self.bias = np.zeros(outc, dtype='f')
133
+
134
+ @staticmethod
135
+ @numba.njit(parallel=True)
136
+ def conv(X, weight, output, h_out, w_out, n, k):
137
+ for i in numba.prange(h_out):
138
+ for j in range(w_out):
139
+ inp = X[:, i:i+k, j:j+k, :].copy().reshape(n, -1)
140
+ out = inp.dot(weight)
141
+ output[:, i, j, :] = out.reshape(n, -1)
142
+
143
+ def forward(self, X):
144
+ self.X = X
145
+ k = self.kernel
146
+ n, h, w, c = X.shape
147
+ h_out = h - (k - 1)
148
+ w_out = w - (k - 1)
149
+
150
+ output = np.tile(self.bias, (n, h_out, w_out, 1))
151
+ weights = self.weights.reshape(-1, self.outc)
152
+ self.conv(X, weights, output, h_out, w_out, n, k)
153
+
154
+ return output
155
+
156
+ def backward(self, grad_backward):
157
+ n, h, w, c = grad_backward.shape
158
+ k = self.kernel
159
+ h_in = h + (k - 1)
160
+ w_in = w + (k - 1)
161
+
162
+ self.weights_diff = np.zeros((k, k, self.inc, self.outc), dtype='f')
163
+ for i in range(k):
164
+ for j in range(k):
165
+ # inp = (n, h, w, cin) => (n*h*w, cin) => (cin, n*h*w)
166
+ inp = self.X[:, i:i+h, j:j+w, :].reshape(-1, self.inc).T
167
+ # diff = (n, h, w, cout) => (n*h*w, cout)
168
+ diff_out = grad_backward.reshape(-1, self.outc)
169
+ self.weights_diff[i, j, :, :] = inp.dot(diff_out)
170
+ self.bias_diff = np.sum(grad_backward, axis=(0, 1, 2))
171
+
172
+ pad = k - 1
173
+ grad_backward_pad = np.pad(grad_backward, ((0, 0), (pad, pad), (pad, pad), (0, 0)), 'constant')
174
+ rotated_weight = self.weights[::-1, ::-1, :, :].transpose(0, 1, 3, 2).reshape(-1, self.inc)
175
+ grad_input = np.zeros((n, h_in, w_in, self.inc), dtype='f')
176
+ self.conv(grad_backward_pad, rotated_weight, grad_input, h_in, w_in, n, k)
177
+
178
+ return grad_input
179
+
180
+ class MaxPoolingLayer(Layer):
181
+ def forward(self, X):
182
+ n, h, w, c = X.shape
183
+ assert(h%2==0 and w%2==0)
184
+ X_grid = X.reshape(n, h // 2, 2, w // 2, 2, c)
185
+ out = np.max(X_grid, axis=(2, 4))
186
+ self.mask = (out.reshape(n, h // 2, 1, w // 2, 1, c) == X_grid)
187
+ return out
188
+
189
+ def backward(self, grad_backward):
190
+ n, h, w, c = grad_backward.shape
191
+ grad_backward_grid = grad_backward.reshape(n, h, 1, w, 1, c)
192
+ return (grad_backward_grid * self.mask).reshape(n, h * 2, w * 2, c)
193
+
194
+ class AvgPoolingLayer(Layer):
195
+ def forward(self, X):
196
+ n, h, w, c = X.shape
197
+ assert(h%2==0 and w%2==0)
198
+ X_grid = X.reshape(n, h // 2, 2, w // 2, 2, c)
199
+ out = np.mean(X_grid, axis=(2, 4))
200
+ self.mask = np.ones_like(X_grid) * (1/4)
201
+ return out
202
+
203
+ def backward(self, grad_backward):
204
+ n, h, w, c = grad_backward.shape
205
+ grad_backward_grid = grad_backward.reshape(n, h, 1, w, 1, c)
206
+ return (grad_backward_grid * self.mask).reshape(n, h * 2, w * 2, c)
207
+
208
+ class GlobalAvgPoolingLayer(Layer):
209
+ def forward(self, X):
210
+ n, h, w, c = X.shape
211
+ out = np.mean(X, axis=(1, 2))
212
+ self.mask = np.ones_like(X) * (1/(h*w))
213
+ return out
214
+
215
+ def backward(self, grad_backward):
216
+ n, c = grad_backward.shape
217
+ return grad_backward.reshape(n, 1, 1, c) * self.mask
218
+
219
+ class MseLoss():
220
+ # mean squared error loss
221
+
222
+ def forward(self, y_model, y_true):
223
+ loss = np.sum(0.5 * (y_model-y_true)**2)
224
+ return loss
225
+
226
+ def backward(self, y_model, y_true):
227
+ return y_model - y_true
228
+
229
+ class CrossEntropyLoss():
230
+ def forward(self, logits, y_true):
231
+ # input: model outputs (logits) and true class indices
232
+ # output: softmax cross-entropy loss
233
+ assert(y_true.dtype == np.uint8)
234
+ true_class_logits = logits[np.arange(len(logits)), y_true]
235
+
236
+ cross_entropy = - true_class_logits + np.log(np.sum(np.exp(logits), axis=-1))
237
+ return cross_entropy
238
+
239
+ def backward(self, logits, y_true):
240
+ # convert to one-hot-encoding:
241
+ ones_true_class = np.zeros_like(logits)
242
+ ones_true_class[np.arange(len(logits)),y_true] = 1
243
+
244
+ softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True)
245
+
246
+ return -ones_true_class + softmax
247
+
248
+ class Optimizer():
249
+ def __init__(self, loss_func, learning_rate):
250
+ self.loss_func = loss_func
251
+ self.learning_rate = learning_rate
252
+
253
+ # ADAM parameters
254
+ self.adam_beta1 = 0.9
255
+ self.adam_beta2 = 0.999
256
+ self.adam_t = 0
257
+ self.eps = 1e-8
258
+
259
+ def step(self, model, X, y_true):
260
+ use_logits = isinstance(self.loss_func, CrossEntropyLoss)
261
+
262
+ # forward pass
263
+ y_model = model.forward(X, use_logits)
264
+
265
+ # compute accuracy
266
+ if y_model.shape[1] > 1:
267
+ # multiple outputs: get index of maximum
268
+ y_model_maxidx = y_model.argmax(axis=1)
269
+ n_correct_predictions = np.sum(y_model_maxidx == y_true)
270
+ else:
271
+ # single output: threshold at 0.5
272
+ n_correct_predictions = np.sum((y_model>0.5) == y_true)
273
+
274
+ # compute loss
275
+ loss = self.loss_func.forward(y_model, y_true)
276
+
277
+ # backward pass
278
+ loss_gradient = self.loss_func.backward(y_model, y_true)
279
+
280
+ model.backward(loss_gradient, use_logits)
281
+
282
+ # update
283
+ if self.optimizer == 'sgd':
284
+ for layer in model.layers:
285
+ layer_weights = layer.get_weights()
286
+ layer_gradients = layer.get_gradients()
287
+ for key in layer_weights:
288
+ layer_weights[key] -= self.learning_rate * layer_gradients[key]
289
+
290
+ elif self.optimizer == 'adam':
291
+ self.adam_t += 1
292
+ for layer in model.layers:
293
+ layer_weights = layer.get_weights()
294
+ layer_gradients = layer.get_gradients()
295
+
296
+ for key in layer_weights:
297
+ layer_weights[key] -= self.learning_rate * layer_gradients[key]
298
+
299
+ if self.adam_t == 1:
300
+ # init m and v
301
+ layer.m[key] = np.zeros_like(layer_gradients[key])
302
+ layer.v[key] = np.zeros_like(layer_gradients[key])
303
+
304
+ layer.m[key] = self.adam_beta1 * layer.m[key] + (1 - self.adam_beta1) * layer_gradients[key] / (1 - self.adam_beta1**self.adam_t)
305
+ layer.v[key] = self.adam_beta2 * layer.v[key] + (1 - self.adam_beta2) * np.power(layer_gradients[key], 2) / (1 - self.adam_beta2**self.adam_t)
306
+
307
+ layer_weights[key] -= self.learning_rate / (np.sqrt(layer.v[key]) + self.eps) * layer.m[key]
308
+
309
+ else:
310
+ raise SystemExit('Error: unknown optimizer ' + str(self.optimizer))
311
+
312
+ return loss.sum(), n_correct_predictions
313
+
314
+ def batch_handler(self, X, y, batchsize, shuffle=False):
315
+ assert len(X) == len(y)
316
+ batchsize = min(batchsize, len(y))
317
+
318
+ if shuffle:
319
+ idxs = np.random.permutation((len(y)))
320
+
321
+ for start_idx in range(0, len(X) - batchsize + 1, batchsize):
322
+ if shuffle:
323
+ batch = idxs[start_idx:start_idx + batchsize]
324
+ else:
325
+ batch = slice(start_idx, start_idx + batchsize)
326
+
327
+ yield X[batch,:], y[batch]
328
+
329
+ def train(self, model, X_train, y_train, X_valid=(), y_valid=(),
330
+ n_epochs=10, batchsize=32, optimizer='adam'):
331
+
332
+ self.optimizer = optimizer
333
+
334
+ self.log = {}
335
+ self.log['loss_train'] = []
336
+ self.log['acc_train'] = []
337
+ self.log['acc_valid'] = []
338
+ for epoch in range(n_epochs):
339
+ start_time = time.time()
340
+
341
+ loss_sum = 0
342
+ n_correct_predictions_sum = 0
343
+ for x_batch, y_batch in self.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
344
+ loss, n_correct_predictions = self.step(model, x_batch, y_batch)
345
+ loss_sum += loss
346
+ n_correct_predictions_sum += n_correct_predictions
347
+
348
+ end_time = time.time()
349
+ elapsed_time = end_time - start_time
350
+ print(f"runtime: {elapsed_time:.1f} sec")
351
+ self.log['loss_train'].append(loss_sum)
352
+ self.log['acc_train'].append(n_correct_predictions_sum / len(y_train))
353
+
354
+ if len(X_valid) > 0:
355
+ y_model_valid = model.forward(X_valid)
356
+
357
+ if y_model_valid.shape[1] > 1:
358
+ # multiple outputs: get index of maximum
359
+ y_model_valid = y_model_valid.argmax(axis=1)
360
+ n_correct_predictions_valid = np.mean(y_model_valid == y_valid)
361
+ else:
362
+ # single output: threshold at 0.5
363
+ n_correct_predictions_valid = np.mean((y_model_valid>0.5) == y_valid)
364
+ self.log['acc_valid'].append(n_correct_predictions_valid)
365
+ print(f'Epoch {epoch+1:3d} : loss {loss_sum:7.1f}, acc_train {self.log["acc_train"][-1]:5.3f}, acc_valid {self.log["acc_valid"][-1]:5.3f}')
366
+ else:
367
+ print(f'Epoch {epoch+1:3d} : loss {loss_sum:7.1f}, acc_train {self.log["acc_train"][-1]:5.3f}')
368
+
369
+ # re-initialize ADAM optimizer after each epoch to improve stability
370
+ self.adam_t = 0
371
+
372
+ class NeuralNetwork():
373
+ def __init__(self):
374
+ self.layers = []
375
+
376
+ def add_layer(self, layer):
377
+ self.layers.append(layer)
378
+
379
+ def forward(self, X, use_logits = False):
380
+ if use_logits:
381
+ # skip last activation layer
382
+ end = len(self.layers) - 1
383
+ else:
384
+ end = len(self.layers)
385
+
386
+ for layer in self.layers[:end]:
387
+ X = layer.forward(X)
388
+ return X
389
+
390
+ def backward(self, gradient_backward, use_logits = False):
391
+ if use_logits:
392
+ # skip last activation layer
393
+ start = len(self.layers) - 2
394
+ else:
395
+ start = len(self.layers) - 1
396
+
397
+ for layer in self.layers[start::-1]:
398
+ gradient_backward = layer.backward(gradient_backward)
399
+
400
+ if __name__ == '__main__':
401
+ #testcase = 'xor'
402
+ #testcase = 'mnist_fcn' # fast fully-connected network, more overfitting
403
+ testcase = 'mnist_lenet' # original LeNet CNN
404
+
405
+ if testcase == 'xor':
406
+ model = NeuralNetwork()
407
+ use_sigmoid = True
408
+ if use_sigmoid:
409
+ np.random.seed(1)
410
+ learning_rate = 2 # for Sigmoid activation function
411
+ model.add_layer(FullyConnectedLayer(n_inputs=2, n_outputs=2))
412
+ model.add_layer(Sigmoid())
413
+ model.add_layer(FullyConnectedLayer(n_inputs=2, n_outputs=1))
414
+ model.add_layer(Sigmoid())
415
+ else:
416
+ np.random.seed(2)
417
+ learning_rate = 0.1 # for ReLU activation function
418
+ model.add_layer(FullyConnectedLayer(n_inputs=2, n_outputs=2))
419
+ model.add_layer(LeakyReLU())
420
+ model.add_layer(FullyConnectedLayer(n_inputs=2, n_outputs=1))
421
+ model.add_layer(LeakyReLU())
422
+
423
+ loss_func = MseLoss()
424
+
425
+ # x1 x2
426
+ X_train = np.array((( 0, 0),
427
+ ( 1, 0),
428
+ ( 0, 1),
429
+ ( 1, 1)))
430
+
431
+ # desired output: logical XOR
432
+ y_train = np.array((1,
433
+ 0,
434
+ 0,
435
+ 1)).reshape((4,1))
436
+
437
+ X_test = X_train
438
+ y_test = y_train
439
+
440
+ batchsize = 4
441
+ n_epochs = 1000
442
+ optim = 'sgd'
443
+
444
+ elif testcase == 'mnist_fcn':
445
+ import dataloader_mnist
446
+
447
+ X_train, y_train = mnist_loader.load_train(num_images = 60000)
448
+ X_test, y_test = mnist_loader.load_valid(num_images = 10000)
449
+
450
+ X_train = X_train[:,2:-2,2:-2,0].reshape(X_train.shape[0], -1)
451
+ X_test = X_test[:,2:-2,2:-2,0].reshape(X_test.shape[0], -1)
452
+
453
+ # show some numbers
454
+ #fig, ax = plt.subplots(1,12, figsize=(12,1), dpi=100)
455
+ #for axis, idx in zip(fig.axes, np.arange(0, 0+12)):
456
+ # axis.imshow(X_train[idx, :].reshape(28,28), cmap='gray')
457
+ # axis.axis('off')
458
+ #plt.show()
459
+
460
+ model = NeuralNetwork()
461
+ model.add_layer(FullyConnectedLayer(n_inputs=28**2, n_outputs=100))
462
+ model.add_layer(ReLU())
463
+ model.add_layer(FullyConnectedLayer(n_inputs=100, n_outputs=200))
464
+ model.add_layer(ReLU())
465
+ model.add_layer(FullyConnectedLayer(n_inputs=200, n_outputs=10))
466
+ model.add_layer(Softmax())
467
+
468
+ loss_func = CrossEntropyLoss()
469
+
470
+ learning_rate = 0.001
471
+ n_epochs = 25
472
+ batchsize = 100
473
+ optim = 'adam'
474
+
475
+ elif testcase == 'mnist_lenet':
476
+ import dataloader_mnist
477
+
478
+ X_train, y_train = mnist_loader.load_train(num_images = 60000)
479
+ X_test, y_test = mnist_loader.load_valid(num_images = 10000)
480
+
481
+ # show some numbers
482
+ #fig, ax = plt.subplots(1,12, figsize=(12,1), dpi=100)
483
+ #for axis, idx in zip(fig.axes, np.arange(0, 0+12)):
484
+ # axis.imshow(X_train[idx, :].reshape(28,28), cmap='gray')
485
+ # axis.axis('off')
486
+ #plt.show()
487
+
488
+ model = NeuralNetwork()
489
+ model.add_layer(ConvolutionalLayer(5, 1, 6))
490
+ model.add_layer(ReLU())
491
+ model.add_layer(AvgPoolingLayer())
492
+ model.add_layer(ConvolutionalLayer(5, 6, 16))
493
+ model.add_layer(ReLU())
494
+ model.add_layer(AvgPoolingLayer())
495
+ model.add_layer(Flatten())
496
+ model.add_layer(FullyConnectedLayer(n_inputs=400, n_outputs=120))
497
+ model.add_layer(ReLU())
498
+ model.add_layer(FullyConnectedLayer(n_inputs=120, n_outputs=84))
499
+ model.add_layer(ReLU())
500
+ model.add_layer(FullyConnectedLayer(n_inputs=84, n_outputs=10))
501
+ model.add_layer(Softmax())
502
+
503
+ loss_func = CrossEntropyLoss()
504
+
505
+ learning_rate = 0.001
506
+ n_epochs = 50 # 20 is enough, test acc stagnates at ~98.0%
507
+ # 50 for AvgPooling, test acc <=98.5%
508
+ batchsize = 32
509
+ optim = 'adam'
510
+
511
+ optimizer = Optimizer(loss_func, learning_rate)
512
+ optimizer.train(model, X_train, y_train, X_test, y_test,
513
+ n_epochs, batchsize, optim)
514
+
515
+ plt.plot(optimizer.log['loss_train'], label='training loss')
516
+ plt.legend(loc='best')
517
+ plt.grid()
518
+ plt.show()
519
+
520
+ plt.plot(optimizer.log['acc_train'], label='training accuracy')
521
+ plt.plot(optimizer.log['acc_valid'], label='valid accuracy')
522
+ plt.legend(loc='best')
523
+ plt.grid()
524
+ plt.show()
@@ -0,0 +1,108 @@
1
+ import numba
2
+ import numpy as np
3
+
4
+ from multiprocessing import Pool
5
+
6
+ #@numba.guvectorize(['f4(f4[:,:,:,:], f4[:,:,:,:], f4[:],i64,i64,i64,i64,i64)'], "(m,n),(n,p)->(m,p)")
7
+ def conv_wsum(X, W, b, ni, i, j, c, co):
8
+ k = 5
9
+ wsum = 0 # np.float32(b[co])
10
+
11
+ for wi in range(k):
12
+ for wj in range(k):
13
+ for ci in range(c):
14
+ wsum += W[wi,wj,ci,co] * X[ni,i+wi,j+wj,ci]
15
+ return wsum
16
+
17
+ #@numba.guvectorize([(numba.float32[:,:,:,:], numba.float32[:,:,:,:], numba.int64, numba.int64, numba.int64, numba.int64, numba.int64, numba.int64, numba.float32)], '(),(),(),(),(),(),(),()->()')
18
+ #def conv_w(W, X, wi, ci, co, ni, i, j, wsum):
19
+ # for wj in range(k):
20
+ # wsum += W[wi,wj,ci,co] * X[ni,i+wi,j+wj,ci]#
21
+ #
22
+ # #for i in range(x.shape[0]):
23
+ # # res[i] = x[i] + y
24
+
25
+ @numba.njit('f4[:,:,:,:](f4[:,:,:,:], f4[:,:,:,:], f4[:])', parallel=True)
26
+ def conv(X, W, b):
27
+ k = 5
28
+ n, h, w, c = X.shape
29
+ h_out = h - (k - 1)
30
+ w_out = w - (k - 1)
31
+ c_out = W.shape[-1]
32
+
33
+ output = np.zeros((n, h_out, w_out, c_out), dtype=np.float32)
34
+ weight = W
35
+
36
+ for ni in numba.prange(n):
37
+ #for ni in range(n):
38
+ for i in range(h_out):
39
+ for j in range(w_out):
40
+ for co in range(c_out):
41
+ wsum = b[co]
42
+ #wsum = conv_wsum(X, W, b, ni, i, j, c, co)
43
+ for ci in range(c):
44
+ for wi in range(k):
45
+ for wj in range(k):
46
+ wsum += W[wi,wj,ci,co] * X[ni,i+wi,j+wj,ci]
47
+
48
+ output[ni, i, j, co] = wsum
49
+
50
+ return output
51
+
52
+ @numba.njit(parallel=True) # 'f4[:,:,:,:](f4[:,:,:,:], f4[:,:,:,:], f4[:])') # , parallel=True)
53
+ def conv_refp(X, W, b):
54
+ k = 5
55
+ n, h, w, c = X.shape
56
+ h_out = h - (k - 1)
57
+ w_out = w - (k - 1)
58
+ c_out = W.shape[-1]
59
+
60
+ output = np.zeros((n, h_out, w_out, c_out), dtype=np.float32)
61
+ weight = W.copy().reshape(-1, c_out)
62
+
63
+ for i in numba.prange(h_out):
64
+ #for i in range(h_out):
65
+ for j in range(w_out):
66
+ inp = X[:, i:i+k, j:j+k, :].copy().reshape(n, -1)
67
+ out = inp.dot(weight) + b
68
+ output[:, i, j, :] = out.reshape(n, -1)
69
+
70
+ return output
71
+
72
+ def conv_ref(X, W, b):
73
+ k = 5
74
+ n, h, w, c = X.shape
75
+ h_out = h - (k - 1)
76
+ w_out = w - (k - 1)
77
+ c_out = W.shape[-1]
78
+
79
+ output = np.zeros((n, h_out, w_out, c_out), dtype=np.float32)
80
+ weight = W.reshape(-1, c_out)
81
+
82
+ for i in range(h_out):
83
+ for j in range(w_out):
84
+ inp = X[:, i:i+k, j:j+k, :].reshape(n, -1)
85
+ out = inp.dot(weight) + b
86
+ output[:, i, j, :] = out.reshape(n, -1)
87
+
88
+ return output
89
+
90
+
91
+ X = np.random.randn(100, 32, 32, 10).astype(np.float32)
92
+ W = np.random.normal(0.0, 1.0, size=(5, 5, 10, 6)).astype(np.float32)
93
+ b = np.random.normal(0.0, 1.0, size=(6)).astype(np.float32)
94
+
95
+ k = 5
96
+ n, h, w, c = X.shape
97
+ h_out = h - (k - 1)
98
+ w_out = w - (k - 1)
99
+ c_out = W.shape[-1]
100
+
101
+
102
+ %timeit out = conv_refp(X, W, b)
103
+ %timeit out_ref = conv_ref(X, W, b)
104
+
105
+ out = conv_refp(X, W, b)
106
+ out_ref = conv_ref(X, W, b)
107
+ err = np.abs(out - out_ref).max()
108
+ print(f"Error: {err}")
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: netlite
3
+ Version: 0.0.1
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
+ Description-Content-Type: text/markdown
14
+
15
+ # NetLite
16
+
17
+ A small white-box training framework for neural networks for education.
18
+
19
+
20
+
21
+ ## References
22
+
23
+ [LeNet5](https://github.com/chuanqi305/LeNet5): A plain numpy implementation of LeNet5 with convolutional layers.
24
+ [JB Grabowski](http://www.jbgrabowski.com/notebooks/neural-net/): A Jupyter notebook using ADAM optimization for fully connected layers.
@@ -0,0 +1,9 @@
1
+ netlite/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ netlite/dataloader_cifar10.py,sha256=TaK8n27ckYKRiEZ5sb_cg9_XVJLl63e-HbiaXO6AUsI,3371
3
+ netlite/dataloader_mnist.py,sha256=-Ucjd56aArHZkjNcdwFhPmH5vg8-1Aqs_DoJ6MPkV4E,3625
4
+ netlite/netlite.py,sha256=DX0gyoRtugzi5T-70zsqExACsAsrn7A0_7W_SdWxAWg,19276
5
+ netlite/netlite_test_convolution.py,sha256=MAOJRUv3mfvwQNPhiZqJxDKYtkboAfIPXI-TM8Eg3FU,3262
6
+ netlite-0.0.1.dist-info/METADATA,sha256=JZ8HgRgYGqrJuwnC-gjt1-EB8YtrXy-u90e-K8LIYRE,863
7
+ netlite-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
8
+ netlite-0.0.1.dist-info/licenses/LICENSE,sha256=LjPlYOoBQ4yGo5S6qTr_UM2FQ00SbksNIfVGmVwDs4E,1096
9
+ netlite-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +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
21
+ SOFTWARE.