netlite 0.0.2__tar.gz → 0.0.4__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.
Files changed (25) hide show
  1. {netlite-0.0.2 → netlite-0.0.4}/.gitignore +1 -0
  2. {netlite-0.0.2 → netlite-0.0.4}/PKG-INFO +3 -5
  3. {netlite-0.0.2 → netlite-0.0.4}/README.md +2 -1
  4. netlite-0.0.4/examples/netlite_example_fit_regression_line.py +65 -0
  5. netlite-0.0.4/examples/netlite_example_lenet_cifar10.py +109 -0
  6. {netlite-0.0.2/src → netlite-0.0.4/examples}/netlite_example_lenet_mnist.py +11 -4
  7. {netlite-0.0.2/src → netlite-0.0.4/examples}/netlite_example_xor_classifier.py +9 -3
  8. netlite-0.0.4/package_build.sh +3 -0
  9. netlite-0.0.4/package_upload.sh +1 -0
  10. {netlite-0.0.2 → netlite-0.0.4}/pyproject.toml +1 -4
  11. netlite-0.0.4/requirements.txt +2 -0
  12. netlite-0.0.4/src/netlite/__init__.py +22 -0
  13. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/dataloader_cifar10.py +7 -3
  14. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/dataloader_mnist.py +22 -18
  15. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/layers.py +101 -39
  16. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/loss_functions.py +42 -2
  17. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/neural_network.py +21 -1
  18. {netlite-0.0.2 → netlite-0.0.4}/src/netlite/optimizer.py +1 -1
  19. netlite-0.0.2/package_build.sh +0 -3
  20. netlite-0.0.2/package_upload.sh +0 -1
  21. netlite-0.0.2/src/netlite/__init__.py +0 -12
  22. {netlite-0.0.2 → netlite-0.0.4}/LICENSE +0 -0
  23. {netlite-0.0.2 → netlite-0.0.4}/images/lenet_mnist_acc_curves.svg +0 -0
  24. {netlite-0.0.2/src → netlite-0.0.4/tests}/netlite_test.py +0 -0
  25. {netlite-0.0.2/src → netlite-0.0.4/tests}/netlite_test_convolution.py +0 -0
@@ -1,3 +1,4 @@
1
1
  dist
2
2
  __pycache__
3
3
  mnist_raw
4
+ cifar10_raw
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: netlite
3
- Version: 0.0.2
3
+ Version: 0.0.4
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
@@ -10,12 +10,9 @@ License-File: LICENSE
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Requires-Python: >=3.9
13
- Requires-Dist: gzip
14
13
  Requires-Dist: matplotlib
15
14
  Requires-Dist: numba
16
15
  Requires-Dist: numpy
17
- Requires-Dist: pickle
18
- Requires-Dist: urllib
19
16
  Description-Content-Type: text/markdown
20
17
 
21
18
  # NetLite
@@ -26,7 +23,8 @@ NetLite provides a light-weight training framework, designed for readability
26
23
  for learning the basic principles of neural networks in AI classes.
27
24
 
28
25
  **Performance:**
29
- - On LeNet, this framework achieves 99% accuracy on the MNIST validation data in just 150 seconds (on my laptop cpu).
26
+ - 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).
27
+ - Optimizations:
30
28
  - computation using numpy for most operations
31
29
  - just-in-time compilation using numba for convolutions
32
30
  - Data-loader allows to limit the number of images used, e.g. to train on just 10% of the MNIST data,
@@ -6,7 +6,8 @@ NetLite provides a light-weight training framework, designed for readability
6
6
  for learning the basic principles of neural networks in AI classes.
7
7
 
8
8
  **Performance:**
9
- - On LeNet, this framework achieves 99% accuracy on the MNIST validation data in just 150 seconds (on my laptop cpu).
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:
10
11
  - computation using numpy for most operations
11
12
  - just-in-time compilation using numba for convolutions
12
13
  - Data-loader allows to limit the number of images used, e.g. to train on just 10% of the MNIST data,
@@ -0,0 +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()
@@ -0,0 +1,109 @@
1
+ import numpy as np
2
+ import time
3
+ import matplotlib.pyplot as plt
4
+ import sys
5
+ import os
6
+
7
+ # add parent folder with netlite source to path
8
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
9
+ sys.path.insert(0, parent_dir)
10
+ import netlite as nl
11
+
12
+ def training_loop(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
13
+ log = {}
14
+ log['loss_train'] = []
15
+ log['loss_valid'] = []
16
+ log['acc_train'] = []
17
+ log['acc_valid'] = []
18
+ for epoch in range(n_epochs):
19
+
20
+ ### Training ###
21
+ start_time = time.time()
22
+ loss_sum = 0
23
+ n_correct_sum = 0
24
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
25
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
26
+ loss_sum += loss
27
+ n_correct_sum += metrics['n_correct']
28
+
29
+ end_time = time.time()
30
+ elapsed_time = end_time - start_time
31
+ print(f"runtime: {elapsed_time:.1f} sec")
32
+
33
+ loss_train_mean = loss_sum / len(y_train)
34
+ log['loss_train'].append(loss_train_mean)
35
+ log['acc_train'].append(n_correct_sum / len(y_train))
36
+
37
+ ### Validation ###
38
+ loss_sum = 0
39
+ n_correct_sum = 0
40
+ for x_batch, y_batch in nl.batch_handler(X_valid, y_valid, batchsize=batchsize, shuffle=False):
41
+ loss, metrics = optimizer.step(model, x_batch, y_batch, forward_only=True)
42
+ loss_sum += loss
43
+ n_correct_sum += metrics['n_correct']
44
+
45
+ loss_valid_mean = loss_sum / len(y_valid)
46
+ log['loss_valid'].append(loss_valid_mean)
47
+ log['acc_valid'].append(n_correct_sum / len(y_valid))
48
+ 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}')
49
+
50
+ return log
51
+
52
+
53
+ X_train, y_train = nl.dataloader_cifar10.load_train(num_images = 50000)
54
+ X_test, y_test = nl.dataloader_cifar10.load_valid(num_images = 10000)
55
+
56
+ # show some numbers
57
+ fig, ax = plt.subplots(1, 6, figsize=(6,1), dpi=100)
58
+ for axis, idx in zip(fig.axes, np.arange(0, 6)):
59
+ axis.imshow(X_train[idx, :, :, :], cmap='gray')
60
+ axis.axis('off')
61
+ plt.show()
62
+
63
+ model = nl.NeuralNetwork([
64
+ nl.BatchNorm(),
65
+ nl.ConvolutionalLayer(5, 3, 32),
66
+ nl.ReLU(),
67
+ nl.MaxPoolingLayer(),
68
+ nl.BatchNorm(),
69
+ nl.ConvolutionalLayer(5, 32, 64),
70
+ nl.ReLU(),
71
+ nl.MaxPoolingLayer(),
72
+ nl.Flatten(),
73
+ nl.BatchNorm(),
74
+ nl.FullyConnectedLayer(n_inputs=5*5*64, n_outputs=120),
75
+ nl.ReLU(),
76
+ nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
77
+ nl.ReLU(),
78
+ nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
79
+ nl.Softmax(),
80
+ ])
81
+ loss_func = nl.CrossEntropyLoss()
82
+
83
+ learning_rate = 0.001
84
+ n_epochs = 20 # test acc at ~70% with MaxPooling
85
+ batchsize = 32
86
+
87
+ optimizer = nl.OptimizerADAM(loss_func, learning_rate)
88
+
89
+ log = training_loop(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
90
+
91
+ plt.plot(log['loss_train'], label='training')
92
+ plt.plot(log['loss_valid'], label='validation')
93
+ plt.legend(loc='best')
94
+ plt.xlabel('epoch')
95
+ plt.ylabel('loss')
96
+ plt.title('Training LeNet on CIFAR10 data')
97
+ plt.grid()
98
+ plt.show()
99
+
100
+ plt.plot(log['acc_train'], label='training')
101
+ plt.plot(log['acc_valid'], label='validation')
102
+ plt.legend(loc='best')
103
+ plt.xlabel('epoch')
104
+ plt.ylabel('accuracy')
105
+ plt.title('Training LeNet on CIFAR10 data')
106
+ plt.grid()
107
+ #plt.savefig("lenet_cifar10_acc_curves.svg")
108
+ plt.show()
109
+
@@ -1,10 +1,15 @@
1
1
  import numpy as np
2
2
  import time
3
3
  import matplotlib.pyplot as plt
4
+ import sys
5
+ import os
4
6
 
7
+ # add parent folder with netlite source to path
8
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
9
+ sys.path.insert(0, parent_dir)
5
10
  import netlite as nl
6
11
 
7
- def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
12
+ def training_loop(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
8
13
  log = {}
9
14
  log['loss_train'] = []
10
15
  log['loss_valid'] = []
@@ -56,10 +61,10 @@ for axis, idx in zip(fig.axes, np.arange(0, 6)):
56
61
  plt.show()
57
62
 
58
63
  model = nl.NeuralNetwork([
59
- nl.ConvolutionalLayer(5, 1, 6),
64
+ nl.ConvolutionalLayer(kernel_size=5, in_channels=1, out_channels=6),
60
65
  nl.ReLU(),
61
66
  nl.AvgPoolingLayer(),
62
- nl.ConvolutionalLayer(5, 6, 16),
67
+ nl.ConvolutionalLayer(kernel_size=5, in_channels=6, out_channels=16),
63
68
  nl.ReLU(),
64
69
  nl.AvgPoolingLayer(),
65
70
  nl.Flatten(),
@@ -70,6 +75,8 @@ model = nl.NeuralNetwork([
70
75
  nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
71
76
  nl.Softmax(),
72
77
  ])
78
+
79
+ model.print(input_shape=(1,32,32,1))
73
80
  loss_func = nl.CrossEntropyLoss()
74
81
 
75
82
  learning_rate = 0.001
@@ -78,7 +85,7 @@ batchsize = 32
78
85
 
79
86
  optimizer = nl.OptimizerADAM(loss_func, learning_rate)
80
87
 
81
- log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
88
+ log = training_loop(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
82
89
 
83
90
  plt.plot(log['loss_train'], label='training')
84
91
  plt.plot(log['loss_valid'], label='validation')
@@ -1,9 +1,14 @@
1
1
  import numpy as np
2
2
  import matplotlib.pyplot as plt
3
+ import sys
4
+ import os
3
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)
4
9
  import netlite as nl
5
-
6
- def train(model, optimizer, X_train, y_train, n_epochs=10, batchsize=32):
10
+
11
+ def training_loop(model, optimizer, X_train, y_train, n_epochs=10, batchsize=32):
7
12
  log = {}
8
13
  log['loss_train'] = []
9
14
  log['acc_train'] = []
@@ -30,6 +35,7 @@ model = nl.NeuralNetwork([
30
35
  nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
31
36
  nl.Sigmoid(),
32
37
  ])
38
+ model.print(input_shape=(4,2))
33
39
 
34
40
  # input x1 x2
35
41
  X_train = np.array((( 0, 0),
@@ -45,7 +51,7 @@ y_train = np.array((1,
45
51
 
46
52
  optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
47
53
 
48
- log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
54
+ log = training_loop(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
49
55
 
50
56
  plt.plot(log['loss_train'], label='training')
51
57
  plt.legend(loc='best')
@@ -0,0 +1,3 @@
1
+ rm -rf dist
2
+ python -m build
3
+
@@ -0,0 +1 @@
1
+ twine upload dist/*
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "netlite"
7
- version = "0.0.2"
7
+ version = "0.0.4"
8
8
  authors = [
9
9
  { name="Hanno Homann", email="hanno.homann@example.com" },
10
10
  ]
@@ -18,12 +18,9 @@ classifiers = [
18
18
  license = "MIT"
19
19
  license-files = ["LICENSE"]
20
20
  dependencies = [
21
- "gzip",
22
21
  "matplotlib",
23
22
  "numpy",
24
23
  "numba",
25
- "pickle",
26
- "urllib",
27
24
  ]
28
25
 
29
26
  [project.urls]
@@ -0,0 +1,2 @@
1
+ build
2
+ twine
@@ -0,0 +1,22 @@
1
+ # make imports from layers.py etc available in the package name 'netlite',
2
+ # e.g. allow
3
+ # import netlite as nl
4
+ # l1 = nl.ReLU()
5
+
6
+ from .layers import *
7
+ from .loss_functions import *
8
+ from .neural_network import *
9
+ from .optimizer import *
10
+
11
+ from .dataloader_mnist import *
12
+ from .dataloader_cifar10 import *
13
+
14
+ # set nl.__version__
15
+ try:
16
+ from importlib.metadata import version, PackageNotFoundError
17
+ except ImportError: # for Python < 3.8
18
+ from importlib_metadata import version, PackageNotFoundError
19
+ try:
20
+ __version__ = version("netlite") # get version from pyproject.toml
21
+ except PackageNotFoundError:
22
+ __version__ = "0.0.0" # fallback if not installed
@@ -2,6 +2,7 @@
2
2
  import numpy as np
3
3
  import matplotlib.pyplot as plt
4
4
 
5
+ import sys
5
6
  import os.path
6
7
  import tarfile
7
8
  import urllib.request
@@ -38,9 +39,12 @@ def download(download_dir, filename):
38
39
 
39
40
  def extract(download_dir, filename):
40
41
  targetfile = os.path.join(download_dir, filename)
41
- tar_file = tarfile.open(targetfile)
42
- tar_file.extractall(download_dir)
43
- tar_file.close()
42
+
43
+ with tarfile.open(targetfile) as tar:
44
+ if sys.version_info >= (3, 12):
45
+ tar.extractall(path=download_dir, filter=lambda m, _: m if m.isreg() else None)
46
+ else:
47
+ tar.extractall(path=download_dir)
44
48
 
45
49
  def load(input_path, images_file, num_images_max):
46
50
  gz_filename = 'cifar-10-python.tar.gz'
@@ -16,27 +16,31 @@ def load_valid(input_path = 'mnist_raw', num_images = 10000):
16
16
  labels_file = 't10k-labels-idx1-ubyte.gz'
17
17
  return load(input_path, images_file, labels_file, num_images)
18
18
 
19
- def download(download_dir, filename):
19
+ def download(download_dir, filename, verbose=False):
20
20
  if not os.path.isdir(download_dir):
21
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
- ]
22
+ mirrors = ["http://yann.lecun.com/exdb/mnist/",
23
+ "https://ossci-datasets.s3.amazonaws.com/mnist/",
24
+ "https://wuecampus.uni-wuerzburg.de/moodle/pluginfile.php/4698779/mod_folder/content/0/",
25
+ ]
27
26
  target_file = os.path.join(download_dir, filename)
28
- print("Downloading '" + filename + "' : ")
29
- for url in urls:
27
+ print("Downloading '" + filename + "' : ", end='')
28
+ for url in mirrors:
30
29
  source_file = url + filename
31
30
  try:
32
- #print(f"Attempting to download: {source_file}")
31
+ if verbose:
32
+ print(f"Attempting to download: {source_file}")
33
33
  urllib.request.urlretrieve(source_file, target_file)
34
- #print(f"Successfully downloaded: {target_file}")
35
- print('+')
34
+ if verbose:
35
+ print(f"Successfully downloaded: {target_file}")
36
+ else:
37
+ print('+')
36
38
  break
37
39
  except Exception as e:
38
- #print(f"Failed to download {source_file}: {e}")
39
- print('-')
40
+ if verbose:
41
+ print(f"Failed to download {source_file}: {e}")
42
+ else:
43
+ print('-', end='')
40
44
  continue
41
45
 
42
46
  def load(input_path, images_file, labels_file, num_images_max):
@@ -55,9 +59,9 @@ def load(input_path, images_file, labels_file, num_images_max):
55
59
  num_images = int.from_bytes(images_byte.read(4), byteorder='big')
56
60
  img_height = int.from_bytes(images_byte.read(4), byteorder='big')
57
61
  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)
62
+ assert magic_num == 2051, 'invalid raw file'
63
+ assert img_height == 28, 'invalid raw file'
64
+ assert img_width == 28, 'invalid raw file'
61
65
 
62
66
  num_images_max = min(num_images, num_images_max)
63
67
 
@@ -70,8 +74,8 @@ def load(input_path, images_file, labels_file, num_images_max):
70
74
  # read labels
71
75
  magic_num = int.from_bytes(labels_byte.read(4), byteorder='big')
72
76
  num_labels = int.from_bytes(labels_byte.read(4), byteorder='big')
73
- assert(magic_num == 2049)
74
- assert(num_labels == num_images)
77
+ assert magic_num == 2049, 'invalid label file'
78
+ assert num_labels == num_images, 'invalid label file'
75
79
 
76
80
  buf = labels_byte.read(num_images_max)
77
81
  labels = np.frombuffer(buf, dtype=np.uint8)
@@ -15,6 +15,14 @@ class Layer(ABC):
15
15
  '''Propagate gradient backward through the layer.'''
16
16
  pass
17
17
 
18
+ def print(self, Xin):
19
+ '''Print layer properties.'''
20
+ Xout = self.forward(Xin)
21
+ print(f'- {self.__class__.__name__}:')
22
+ print(f' - in ={Xin.shape}')
23
+ print(f' - out={Xout.shape}')
24
+ return Xout
25
+
18
26
  def get_weights(self):
19
27
  '''Return a dictionary of named trainable parameters.
20
28
  The parameters are returned by reference to a numpy array
@@ -26,7 +34,9 @@ class Layer(ABC):
26
34
  return {} # default: no trainable parameters
27
35
 
28
36
  class FullyConnectedLayer(Layer):
29
- '''Fully connected aka Dense layer'''
37
+ '''Fully connected aka Dense layer
38
+ - data order: (batch, channels)
39
+ '''
30
40
  def __init__(self, n_inputs, n_outputs):
31
41
  # n_inputs: number of input channels
32
42
  # n_outputs: number of output channels
@@ -36,11 +46,13 @@ class FullyConnectedLayer(Layer):
36
46
  self.initialize_weights()
37
47
 
38
48
  def initialize_weights(self):
39
- stddev = np.sqrt(2.0 / (self.n_inputs)) # msra
49
+ stddev = np.sqrt(2.0 / (self.n_inputs)) # msra initialization
40
50
  self.weights = np.random.normal(0.0, stddev, size=(self.n_inputs, self.n_outputs)).astype('f')
41
51
  self.bias = np.zeros((1, self.n_outputs), dtype='f')
42
52
 
43
53
  def forward(self, X):
54
+ assert len(X.shape)==2, 'FullyConnectedLayer: input must have dim=2'
55
+ assert X.shape[1] == self.n_inputs, 'FullyConnectedLayer: invalid number of input channels'
44
56
  self.X = X
45
57
  return X @ self.weights + self.bias
46
58
 
@@ -62,17 +74,20 @@ class FullyConnectedLayer(Layer):
62
74
  return {'weights' : self.grad_weights, 'bias': self.grad_bias}
63
75
 
64
76
  class ConvolutionalLayer(Layer):
65
- def __init__(self, kernel_width, inc, outc):
66
- self.kernel_width = kernel_width
67
- self.inc = inc
68
- self.outc = outc
77
+ '''Convolutional layer
78
+ - data order: (batch, height, width, channels)
79
+ '''
80
+ def __init__(self, kernel_size, in_channels, out_channels):
81
+ self.kernel_size = kernel_size
82
+ self.in_channels = in_channels
83
+ self.out_channels = out_channels
69
84
  self.initialize_weights()
70
85
 
71
86
  def initialize_weights(self):
72
- k = self.kernel_width
73
- stddev = np.sqrt(2.0 / (k**2 * self.inc)) # msra
74
- self.weights = np.random.normal(0.0, stddev, size=(k, k, self.inc, self.outc)).astype('f')
75
- self.bias = np.zeros(self.outc, dtype='f')
87
+ k = self.kernel_size
88
+ stddev = np.sqrt(2.0 / (k**2 * self.in_channels)) # msra initialization
89
+ self.weights = np.random.normal(0.0, stddev, size=(k, k, self.in_channels, self.out_channels)).astype('f')
90
+ self.bias = np.zeros(self.out_channels, dtype='f')
76
91
 
77
92
  @staticmethod
78
93
  @numba.njit(parallel=True)
@@ -84,40 +99,44 @@ class ConvolutionalLayer(Layer):
84
99
  output[:, i, j, :] = out.reshape(n, -1)
85
100
 
86
101
  def forward(self, X):
102
+ assert len(X.shape)==4, 'ConvolutionalLayer: input must have dim=4'
103
+ assert X.dtype==np.float32, 'ConvolutionalLayer: input dtype must be float32'
87
104
  self.X = X
88
- k = self.kernel_width
105
+ k = self.kernel_size
89
106
  n, h, w, c = X.shape
90
107
  h_out = h - (k - 1)
91
108
  w_out = w - (k - 1)
92
109
 
93
110
  output = np.tile(self.bias, (n, h_out, w_out, 1))
94
- weights = self.weights.reshape(-1, self.outc)
111
+ weights = self.weights.reshape(-1, self.out_channels)
95
112
  self.conv(X, weights, output, h_out, w_out, n, k)
96
113
 
97
114
  return output
98
115
 
99
116
  def backward(self, grad_backward):
100
117
  n, h, w, c = grad_backward.shape
101
- k = self.kernel_width
118
+ k = self.kernel_size
102
119
  h_in = h + (k - 1)
103
120
  w_in = w + (k - 1)
104
121
 
105
- self.grad_weights = np.zeros((k, k, self.inc, self.outc), dtype='f')
122
+ # compute gradients for weights
123
+ self.grad_weights = np.zeros((k, k, self.in_channels, self.out_channels), dtype='f')
106
124
  for i in range(k):
107
125
  for j in range(k):
108
- # inp = (n, h, w, cin) => (n*h*w, cin) => (cin, n*h*w)
109
- inp = self.X[:, i:i+h, j:j+w, :].reshape(-1, self.inc).T
110
- # diff = (n, h, w, cout) => (n*h*w, cout)
111
- diff_out = grad_backward.reshape(-1, self.outc)
112
- self.grad_weights[i, j, :, :] = inp.dot(diff_out)
126
+ # reshape input: (n, h, w, cin) --> (n*h*w, cin) --> (cin, n*h*w)
127
+ Xr = self.X[:, i:i+h, j:j+w, :].reshape(-1, self.in_channels).T
128
+ # reshape grad_backward: (n, h, w, cout) --> (n*h*w, cout)
129
+ Gr = grad_backward.reshape(-1, self.out_channels)
130
+ self.grad_weights[i, j, :, :] = Xr.dot(Gr)
131
+ # compute gradients for bias
113
132
  self.grad_bias = np.sum(grad_backward, axis=(0, 1, 2))
114
133
 
134
+ # compute and return gradients for input
115
135
  pad = k - 1
116
136
  grad_backward_pad = np.pad(grad_backward, ((0, 0), (pad, pad), (pad, pad), (0, 0)), 'constant')
117
- rotated_weight = self.weights[::-1, ::-1, :, :].transpose(0, 1, 3, 2).reshape(-1, self.inc)
118
- grad_input = np.zeros((n, h_in, w_in, self.inc), dtype='f')
137
+ rotated_weight = self.weights[::-1, ::-1, :, :].transpose(0, 1, 3, 2).reshape(-1, self.in_channels)
138
+ grad_input = np.zeros((n, h_in, w_in, self.in_channels), dtype='f')
119
139
  self.conv(grad_backward_pad, rotated_weight, grad_input, h_in, w_in, n, k)
120
-
121
140
  return grad_input
122
141
 
123
142
  def get_weights(self):
@@ -128,20 +147,6 @@ class ConvolutionalLayer(Layer):
128
147
  # return a dictionary of named gradients
129
148
  return {'weights' : self.grad_weights, 'bias': self.grad_bias}
130
149
 
131
- class MaxPoolingLayer(Layer):
132
- def forward(self, X):
133
- n, h, w, c = X.shape
134
- assert(h%2==0 and w%2==0)
135
- X_grid = X.reshape(n, h // 2, 2, w // 2, 2, c)
136
- out = np.max(X_grid, axis=(2, 4))
137
- self.mask = (out.reshape(n, h // 2, 1, w // 2, 1, c) == X_grid)
138
- return out
139
-
140
- def backward(self, grad_backward):
141
- n, h, w, c = grad_backward.shape
142
- grad_backward_grid = grad_backward.reshape(n, h, 1, w, 1, c)
143
- return (grad_backward_grid * self.mask).reshape(n, h * 2, w * 2, c)
144
-
145
150
  class ReLU(Layer):
146
151
  '''Rectified linear unit activation'''
147
152
  def forward(self, X):
@@ -177,6 +182,7 @@ class Sigmoid(Layer):
177
182
  class Softmax(Layer):
178
183
  '''Softmax classifier'''
179
184
  def forward(self, X):
185
+ self.X = X
180
186
  softmax = np.exp(X) / np.exp(X).sum(axis=-1, keepdims=True)
181
187
  return softmax
182
188
 
@@ -188,16 +194,32 @@ class Softmax(Layer):
188
194
  class Flatten(Layer):
189
195
  '''Flatten an input tensor to a vector'''
190
196
  def forward(self, X):
191
- self.X_shape = X.shape
197
+ self.X = X
192
198
  return X.copy().reshape(X.shape[0], -1)
193
199
 
194
200
  def backward(self, grad_backward):
195
- return grad_backward.reshape(self.X_shape)
201
+ return grad_backward.reshape(self.X.shape)
202
+
203
+ class MaxPoolingLayer(Layer):
204
+ def forward(self, X):
205
+ self.X = X
206
+ n, h, w, c = X.shape
207
+ assert h%2==0 and w%2==0, 'input width and height must be even'
208
+ X_grid = X.reshape(n, h // 2, 2, w // 2, 2, c)
209
+ out = np.max(X_grid, axis=(2, 4))
210
+ self.mask = (out.reshape(n, h // 2, 1, w // 2, 1, c) == X_grid)
211
+ return out
212
+
213
+ def backward(self, grad_backward):
214
+ n, h, w, c = grad_backward.shape
215
+ grad_backward_grid = grad_backward.reshape(n, h, 1, w, 1, c)
216
+ return (grad_backward_grid * self.mask).reshape(n, h * 2, w * 2, c)
196
217
 
197
218
  class AvgPoolingLayer(Layer):
198
219
  def forward(self, X):
220
+ self.X = X
199
221
  n, h, w, c = X.shape
200
- assert(h%2==0 and w%2==0)
222
+ assert h%2==0 and w%2==0, 'input width and height must be even'
201
223
  X_grid = X.reshape(n, h // 2, 2, w // 2, 2, c)
202
224
  out = np.mean(X_grid, axis=(2, 4))
203
225
  self.mask = np.ones_like(X_grid) * (1/4)
@@ -210,6 +232,7 @@ class AvgPoolingLayer(Layer):
210
232
 
211
233
  class GlobalAvgPoolingLayer(Layer):
212
234
  def forward(self, X):
235
+ self.X = X
213
236
  n, h, w, c = X.shape
214
237
  out = np.mean(X, axis=(1, 2))
215
238
  self.mask = np.ones_like(X) * (1/(h*w))
@@ -219,3 +242,42 @@ class GlobalAvgPoolingLayer(Layer):
219
242
  n, c = grad_backward.shape
220
243
  return grad_backward.reshape(n, 1, 1, c) * self.mask
221
244
 
245
+ class BatchNorm(Layer):
246
+ def forward(self, X):
247
+ training_mode = (X.shape[0] > 1)
248
+ self.beta = 0.9
249
+ self.eps = 1e-7
250
+
251
+ if training_mode:
252
+ # compute batch statistics
253
+ if len(X.shape)==2:
254
+ batch_mean = np.mean(X, axis=0, keepdims=True)
255
+ batch_var = np.var(X, axis=0, keepdims=True)
256
+ else:
257
+ assert len(X.shape)==4, 'Expecting image tensor.'
258
+ batch_mean = np.mean(X, axis=(0,1,2), keepdims=True)
259
+ batch_var = np.var(X, axis=(0,1,2), keepdims=True)
260
+
261
+ # soft updates
262
+ if not hasattr(self, 'running_mean'):
263
+ # initialization
264
+ self.running_mean = batch_mean
265
+ self.running_var = batch_var
266
+ else:
267
+ self.running_mean = self.beta*self.running_mean + (1-self.beta)*batch_mean
268
+ self.running_var = self.beta*self.running_var + (1-self.beta)*batch_var
269
+
270
+ # normalize
271
+ x_out = (X - self.running_mean) / np.sqrt(self.running_var + self.eps)
272
+ else:
273
+ # Use running averages at inference
274
+ x_out = (X - self.running_mean) / np.sqrt(self.running_var + self.eps)
275
+
276
+ return x_out
277
+
278
+ def backward(self, grad_backward):
279
+ # gradient wrt input
280
+ assert hasattr(self, 'running_var'), 'BatchNorm forward must be called first.'
281
+ dx = grad_backward / np.sqrt(self.running_var + self.eps)
282
+
283
+ return dx
@@ -17,7 +17,7 @@ class LossFunction(ABC):
17
17
  pass
18
18
 
19
19
  class MseLoss(LossFunction):
20
- # mean squared error loss
20
+ '''Mean squared error loss'''
21
21
 
22
22
  def forward(self, y_model, y_true):
23
23
  loss = np.sum(0.5 * (y_model-y_true)**2)
@@ -26,7 +26,46 @@ class MseLoss(LossFunction):
26
26
  def backward(self, y_model, y_true):
27
27
  return y_model - y_true
28
28
 
29
+ class HuberLoss(LossFunction):
30
+ '''Huber loss function
31
+ - Quadratic loss (L2 norm) for small errors (z < delta),
32
+ where delta is approx. the data standard deviation.
33
+ - Linear loss (L1 norm) beyond for robustness against outliers.
34
+ '''
35
+ def __init__(self, delta):
36
+ super().__init__()
37
+ self.delta = delta
38
+
39
+ def forward(self, y_model, y_true):
40
+ z = y_model - y_true
41
+
42
+ idx_quadratic = abs(z) < self.delta
43
+ idx_linear = np.logical_not(idx_quadratic)
44
+
45
+ loss = np.zeros(z.shape)
46
+ loss[idx_quadratic] = 0.5*z[idx_quadratic]**2
47
+ loss[idx_linear] = self.delta * (abs(z[idx_linear]) - 0.5*self.delta)
48
+
49
+ return loss.sum()
50
+
51
+ def backward(self, y_model, y_true):
52
+ z = y_model - y_true
53
+
54
+ idx_quadratic = abs(z) < self.delta
55
+ idx_linear_pos = np.logical_and(np.logical_not(idx_quadratic), z > 0)
56
+ idx_linear_neg = np.logical_and(np.logical_not(idx_quadratic), z < 0)
57
+
58
+ grad = np.zeros(z.shape)
59
+ grad[idx_quadratic] = z[idx_quadratic]
60
+ grad[idx_linear_pos] = self.delta
61
+ grad[idx_linear_neg] = -self.delta
62
+
63
+ return grad
64
+
29
65
  class CrossEntropyLoss(LossFunction):
66
+ ''' Multi-class cross-entroy loss
67
+ for training of a softmax classifier.
68
+ '''
30
69
  def __init__(self):
31
70
  '''The cross-entropy loss is trained using logits as the model output,
32
71
  i.e. the softmax probabilities are not computed during training.'''
@@ -35,7 +74,8 @@ class CrossEntropyLoss(LossFunction):
35
74
  def forward(self, logits, y_true):
36
75
  # input: model outputs (logits) and true class indices
37
76
  # output: softmax cross-entropy loss
38
- assert(y_true.dtype == np.uint8)
77
+ assert np.issubdtype(y_true.dtype, np.integer), f"Expected integer dtype but got {y_true.dtype}"
78
+
39
79
  true_class_logits = logits[np.arange(len(logits)), y_true]
40
80
 
41
81
  cross_entropy = - true_class_logits + np.log(np.sum(np.exp(logits), axis=-1))
@@ -1,3 +1,5 @@
1
+ import numpy as np
2
+
1
3
  class NeuralNetwork():
2
4
  def __init__(self, layers = []):
3
5
  self.layers = layers
@@ -24,4 +26,22 @@ class NeuralNetwork():
24
26
  start = len(self.layers) - 1
25
27
 
26
28
  for layer in self.layers[start::-1]:
27
- gradient_backward = layer.backward(gradient_backward)
29
+ gradient_backward = layer.backward(gradient_backward)
30
+
31
+ def print(self, input_shape=None):
32
+ print(f'Feed-forward network with {len(self.layers)} layers:')
33
+
34
+ if len(self.layers) == 0:
35
+ print('- no layers')
36
+ return
37
+
38
+ if input_shape is None:
39
+ if not hasattr(self.layers[0], 'X'):
40
+ print('forward() has not been called yet - provide input_shape to get layer size info')
41
+ return
42
+ input_shape = self.layers[0].X.shape
43
+
44
+ Xin = np.zeros(input_shape, dtype='f')
45
+ for layer in self.layers:
46
+ Xin = layer.print(Xin)
47
+
@@ -124,7 +124,7 @@ class OptimizerADAM(OptimizerSGD):
124
124
  layer_weights[key] -= self.learning_rate / (np.sqrt(self.v[i][key]) + self.eps) * self.m[i][key]
125
125
 
126
126
  def batch_handler(X, y, batchsize, shuffle=False):
127
- assert len(X) == len(y)
127
+ assert len(X) == len(y), f'Number of data {len(X)} does not match number of labels {len(y)}'
128
128
  batchsize = min(batchsize, len(y))
129
129
 
130
130
  if shuffle:
@@ -1,3 +0,0 @@
1
- rm -rf dist
2
- py -m build
3
-
@@ -1 +0,0 @@
1
- twine upload dist/netlite-0.0.1.tar.gz dist/netlite-0.0.1-py3-none-any.whl
@@ -1,12 +0,0 @@
1
- # make imports from layers.py etc available in the package name 'netlite',
2
- # e.g. allow
3
- # import netlite as nl
4
- # l1 = nl.ReLU()
5
-
6
- from .layers import *
7
- from .loss_functions import *
8
- from .neural_network import *
9
- from .optimizer import *
10
-
11
- from .dataloader_mnist import *
12
- from .dataloader_cifar10 import *
File without changes