netlite 0.0.8__tar.gz → 1.0.0__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 (28) hide show
  1. {netlite-0.0.8 → netlite-1.0.0}/PKG-INFO +2 -1
  2. netlite-1.0.0/package_run_tests.sh +1 -0
  3. {netlite-0.0.8 → netlite-1.0.0}/pyproject.toml +2 -1
  4. netlite-1.0.0/requirements.txt +10 -0
  5. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/layers.py +3 -3
  6. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/loss_functions.py +12 -9
  7. netlite-1.0.0/tests/test_convolution.py +96 -0
  8. netlite-1.0.0/tests/test_netlite.py +177 -0
  9. netlite-0.0.8/requirements.txt +0 -2
  10. netlite-0.0.8/tests/netlite_test.py +0 -169
  11. netlite-0.0.8/tests/netlite_test_convolution.py +0 -108
  12. {netlite-0.0.8 → netlite-1.0.0}/.gitignore +0 -0
  13. {netlite-0.0.8 → netlite-1.0.0}/LICENSE +0 -0
  14. {netlite-0.0.8 → netlite-1.0.0}/README.md +0 -0
  15. {netlite-0.0.8 → netlite-1.0.0}/examples/netlite_example_fit_regression_line.py +0 -0
  16. {netlite-0.0.8 → netlite-1.0.0}/examples/netlite_example_lenet_cifar10.py +0 -0
  17. {netlite-0.0.8 → netlite-1.0.0}/examples/netlite_example_lenet_mnist.py +0 -0
  18. {netlite-0.0.8 → netlite-1.0.0}/examples/netlite_example_xor_classifier.py +0 -0
  19. {netlite-0.0.8 → netlite-1.0.0}/images/lenet_mnist_acc_curves.svg +0 -0
  20. {netlite-0.0.8 → netlite-1.0.0}/images/logo_netlite.png +0 -0
  21. {netlite-0.0.8 → netlite-1.0.0}/package_build.sh +0 -0
  22. {netlite-0.0.8 → netlite-1.0.0}/package_upload.sh +0 -0
  23. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/__init__.py +0 -0
  24. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/dataloader_cifar10.py +0 -0
  25. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/dataloader_mnist.py +0 -0
  26. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/neural_network.py +0 -0
  27. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/numba_optional.py +0 -0
  28. {netlite-0.0.8 → netlite-1.0.0}/src/netlite/optimizer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: netlite
3
- Version: 0.0.8
3
+ Version: 1.0.0
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
@@ -13,6 +13,7 @@ Requires-Python: >=3.9
13
13
  Requires-Dist: matplotlib
14
14
  Requires-Dist: numba
15
15
  Requires-Dist: numpy
16
+ Requires-Dist: scipy
16
17
  Description-Content-Type: text/markdown
17
18
 
18
19
  # NetLite
@@ -0,0 +1 @@
1
+ pytest tests/ -v
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "netlite"
7
- version = "0.0.8"
7
+ version = "1.0.0"
8
8
  authors = [
9
9
  { name="Hanno Homann", email="hanno.homann@example.com" },
10
10
  ]
@@ -21,6 +21,7 @@ dependencies = [
21
21
  "matplotlib",
22
22
  "numpy",
23
23
  "numba",
24
+ "scipy", # needed by numba
24
25
  ]
25
26
 
26
27
  [project.urls]
@@ -0,0 +1,10 @@
1
+ # runtime requirements
2
+ matplotlib
3
+ numpy
4
+ numba
5
+ scipy # needed by numba
6
+
7
+ # build and test requirements
8
+ build
9
+ twine
10
+ pytest
@@ -19,8 +19,8 @@ class Layer(ABC):
19
19
  '''Print layer properties.'''
20
20
  Xout = self.forward(Xin)
21
21
  print(f'- {self.__class__.__name__}:')
22
- print(f' - in ={Xin.shape}')
23
- print(f' - out={Xout.shape}')
22
+ print(f' - in =(:, {', '.join(str(s) for s in Xin.shape[1:])})')
23
+ print(f' - out=(:, {', '.join(str(s) for s in Xout.shape[1:])})')
24
24
  return Xout
25
25
 
26
26
  def get_weights(self):
@@ -96,7 +96,7 @@ class ConvolutionalLayer(Layer):
96
96
  for j in range(w_out):
97
97
  inp = X[:, i:i+k, j:j+k, :].copy().reshape(n, -1)
98
98
  out = inp.dot(weight)
99
- output[:, i, j, :] = out.reshape(n, -1)
99
+ output[:, i, j, :] += out.reshape(n, -1)
100
100
 
101
101
  def forward(self, X):
102
102
  assert len(X.shape)==4, 'ConvolutionalLayer: input must have dim=4'
@@ -8,7 +8,7 @@ class LossFunction(ABC):
8
8
 
9
9
  @abstractmethod
10
10
  def forward(self, X):
11
- '''Propagate input forward through the los.'''
11
+ '''Propagate input forward through the loss.'''
12
12
  pass
13
13
 
14
14
  @abstractmethod
@@ -18,17 +18,16 @@ class LossFunction(ABC):
18
18
 
19
19
  class MseLoss(LossFunction):
20
20
  '''Mean squared error loss'''
21
-
22
21
  def forward(self, y_model, y_true):
23
- loss = np.sum(0.5 * (y_model-y_true)**2)
24
- return loss
22
+ loss = 0.5 * (y_model-y_true)**2
23
+ return loss.sum()
25
24
 
26
25
  def backward(self, y_model, y_true):
27
26
  return y_model - y_true
28
27
 
29
28
  class HuberLoss(LossFunction):
30
29
  '''Huber loss function
31
- - Quadratic loss (L2 norm) for small errors (z < delta),
30
+ - Quadratic loss (L2 norm) for small errors |z| < delta,
32
31
  where delta is approx. the data standard deviation.
33
32
  - Linear loss (L1 norm) beyond for robustness against outliers.
34
33
  '''
@@ -70,16 +69,20 @@ class CrossEntropyLoss(LossFunction):
70
69
  '''The cross-entropy loss is trained using logits as the model output,
71
70
  i.e. the softmax probabilities are not computed during training.'''
72
71
  self.use_logits = True
73
-
72
+
74
73
  def forward(self, logits, y_true):
75
- # input: model outputs (logits) and true class indices
74
+ # input: model outputs (logits) and vector of true class indices
76
75
  # output: softmax cross-entropy loss
77
76
  assert np.issubdtype(y_true.dtype, np.integer), f"Expected integer dtype but got {y_true.dtype}"
78
77
 
79
- true_class_logits = logits[np.arange(len(logits)), y_true]
78
+ batch_size = len(logits)
79
+ assert len(y_true.shape) == 1, "Vector of true class indices should be 1-dimensional."
80
+ assert y_true.shape[0] == batch_size, "Expected exactly one true class per sample."
81
+
82
+ true_class_logits = logits[np.arange(batch_size), y_true]
80
83
 
81
84
  cross_entropy = - true_class_logits + np.log(np.sum(np.exp(logits), axis=-1))
82
- return cross_entropy
85
+ return cross_entropy.sum()
83
86
 
84
87
  def backward(self, logits, y_true):
85
88
  # convert to one-hot-encoding:
@@ -0,0 +1,96 @@
1
+ import numba
2
+ import numpy as np
3
+
4
+ # add parent folder with netlite source to path
5
+ import os
6
+ import sys
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 conv_ref(X, W, b):
12
+ k = 5
13
+ n, h, w, c = X.shape
14
+ h_out = h - (k - 1)
15
+ w_out = w - (k - 1)
16
+ c_out = W.shape[-1]
17
+
18
+ output = np.zeros((n, h_out, w_out, c_out), dtype=np.float32)
19
+ weight = W.reshape(-1, c_out)
20
+
21
+ for i in range(h_out):
22
+ for j in range(w_out):
23
+ inp = X[:, i:i+k, j:j+k, :].reshape(n, -1)
24
+ out = inp.dot(weight) + b
25
+ output[:, i, j, :] = out.reshape(n, -1)
26
+
27
+ return output
28
+
29
+ @numba.njit(parallel=True) # 'f4[:,:,:,:](f4[:,:,:,:], f4[:,:,:,:], f4[:])') # , parallel=True)
30
+ def conv_ref_parallel(X, W, b):
31
+ k = 5
32
+ n, h, w, c = X.shape
33
+ h_out = h - (k - 1)
34
+ w_out = w - (k - 1)
35
+ c_out = W.shape[-1]
36
+
37
+ output = np.zeros((n, h_out, w_out, c_out), dtype=np.float32)
38
+ weight = W.copy().reshape(-1, c_out)
39
+
40
+ for i in numba.prange(h_out):
41
+ for j in range(w_out):
42
+ inp = X[:, i:i+k, j:j+k, :].copy().reshape(n, -1)
43
+ out = inp.dot(weight) + b # adding bias here in the ref implementation
44
+ output[:, i, j, :] += out.reshape(n, -1)
45
+
46
+ return output
47
+
48
+ def test_conv_netlite():
49
+ X = np.random.randn(100, 32, 32, 10).astype(np.float32)
50
+ W = np.random.normal(0.0, 1.0, size=(5, 5, 10, 6)).astype(np.float32)
51
+ b = np.random.normal(0.0, 1.0, size=(6)).astype(np.float32)
52
+ k = 5
53
+ n, h, w, c = X.shape
54
+ c_out = W.shape[-1]
55
+
56
+ layer = nl.ConvolutionalLayer(k, c, c_out)
57
+ layer.weights = W
58
+ layer.bias = b
59
+
60
+ out = layer.forward(X)
61
+ out_ref = conv_ref(X, W, b)
62
+ err = np.abs(out - out_ref).max()
63
+ assert err < 0.00001
64
+
65
+ def test_conv_reference():
66
+ X = np.random.randn(100, 32, 32, 10).astype(np.float32)
67
+ W = np.random.normal(0.0, 1.0, size=(5, 5, 10, 6)).astype(np.float32)
68
+ b = np.random.normal(0.0, 1.0, size=(6)).astype(np.float32)
69
+
70
+ out = conv_ref_parallel(X, W, b)
71
+ out_ref = conv_ref(X, W, b)
72
+ err = np.abs(out - out_ref).max()
73
+ assert err < 0.00001
74
+
75
+ #if __name__ == '__main__':
76
+ #test_conv_netlite()
77
+
78
+ # manual testing, ignored by pytest
79
+ #X = np.random.randn(100, 32, 32, 10).astype(np.float32)
80
+ #W = np.random.normal(0.0, 1.0, size=(5, 5, 10, 6)).astype(np.float32)
81
+ #b = np.random.normal(0.0, 1.0, size=(6)).astype(np.float32)
82
+
83
+ #k = 5
84
+ #n, h, w, c = X.shape
85
+ #h_out = h - (k - 1)
86
+ #w_out = w - (k - 1)
87
+ #c_out = W.shape[-1]
88
+
89
+ # test timing... (unindent needed ?)
90
+ #%timeit out = conv_ref_parallel(X, W, b)
91
+ #%timeit out_ref = conv_ref(X, W, b)
92
+
93
+ #out = conv_ref_parallel(X, W, b)
94
+ #out_ref = conv_ref(X, W, b)
95
+ #err = np.abs(out - out_ref).max()
96
+ #print(f"Error: {err}")
@@ -0,0 +1,177 @@
1
+ import numpy as np
2
+ #import time
3
+ import matplotlib.pyplot as plt
4
+ import pytest
5
+
6
+ # add parent folder with netlite source to path
7
+ import os
8
+ import sys
9
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
10
+ sys.path.insert(0, parent_dir)
11
+ import netlite as nl
12
+
13
+ # fixed random seed for reproducible testing
14
+ np.random.seed(1)
15
+
16
+ def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
17
+ log = {}
18
+ log['loss_train'] = []
19
+ log['loss_valid'] = []
20
+ log['acc_train'] = []
21
+ log['acc_valid'] = []
22
+ for epoch in range(n_epochs):
23
+ #start_time = time.time()
24
+
25
+ loss_sum = 0
26
+ n_correct_sum = 0
27
+ for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
28
+ loss, metrics = optimizer.step(model, x_batch, y_batch)
29
+ loss_sum += loss
30
+ n_correct_sum += metrics['n_correct']
31
+
32
+ #end_time = time.time()
33
+ #elapsed_time = end_time - start_time
34
+ #print(f"runtime: {elapsed_time:.1f} sec")
35
+
36
+ loss_train_mean = loss_sum / len(y_train)
37
+ log['loss_train'].append(loss_train_mean)
38
+ log['acc_train'].append(n_correct_sum / len(y_train))
39
+
40
+ if len(X_valid) > 0: # if validation data is available
41
+ loss_sum_valid, metrics = optimizer.step(model, X_valid, y_valid, forward_only=True)
42
+ loss_valid_mean = loss_sum_valid / len(y_valid)
43
+ log['loss_valid'].append(loss_valid_mean)
44
+ log['acc_valid'].append(metrics['n_correct'] / len(y_valid))
45
+ #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}')
46
+ else:
47
+ pass
48
+ #print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}')
49
+
50
+ return log
51
+
52
+ def test_xor_classifier():
53
+ use_sigmoid = True
54
+ if use_sigmoid:
55
+ learning_rate = 2 # for Sigmoid activation function
56
+
57
+ model = nl.NeuralNetwork([
58
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
59
+ nl.Sigmoid(),
60
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
61
+ nl.Sigmoid(),
62
+ ])
63
+ else:
64
+ # LeakyReLU - does not always converge
65
+ learning_rate = 0.1 # for ReLU activation function
66
+
67
+ model = nl.NeuralNetwork([
68
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
69
+ nl.LeakyReLU(),
70
+ nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
71
+ nl.LeakyReLU(),
72
+ ])
73
+
74
+ loss_func = nl.MseLoss()
75
+
76
+ # x1 x2
77
+ X_train = np.array((( 0, 0),
78
+ ( 1, 0),
79
+ ( 0, 1),
80
+ ( 1, 1)))
81
+
82
+ # desired output: logical XOR
83
+ y_train = np.array((1,
84
+ 0,
85
+ 0,
86
+ 1)).reshape((4,1))
87
+
88
+ X_test = ()
89
+ y_test = ()
90
+
91
+ batchsize = 4
92
+ n_epochs = 1000
93
+ optimizer = nl.OptimizerSGD(loss_func, learning_rate)
94
+
95
+ log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
96
+ assert log['acc_train'][-1] == pytest.approx(1.0)
97
+ #return log
98
+
99
+ def test_mnist_fcn():
100
+ X_train, y_train = nl.dataloader_mnist.load_train(num_images = 600)
101
+ X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 100)
102
+
103
+ model = nl.NeuralNetwork([
104
+ nl.Flatten(), # convert image to vector
105
+ nl.FullyConnectedLayer(n_inputs=32**2, n_outputs=100),
106
+ nl.ReLU(),
107
+ nl.FullyConnectedLayer(n_inputs=100, n_outputs=200),
108
+ nl.ReLU(),
109
+ nl.FullyConnectedLayer(n_inputs=200, n_outputs=10),
110
+ nl.Softmax(),
111
+ ])
112
+
113
+ loss_func = nl.CrossEntropyLoss()
114
+
115
+ learning_rate = 0.001
116
+ n_epochs = 25
117
+ batchsize = 100
118
+
119
+ optimizer = nl.OptimizerADAM(loss_func, learning_rate)
120
+ log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
121
+
122
+ assert log['acc_train'][-1] > 0.9
123
+ #return log
124
+
125
+ def test_mnist_lenet():
126
+ X_train, y_train = nl.dataloader_mnist.load_train(num_images = 600)
127
+ X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 100)
128
+
129
+ model = nl.NeuralNetwork([
130
+ nl.ConvolutionalLayer(5, 1, 6),
131
+ nl.ReLU(),
132
+ nl.AvgPoolingLayer(),
133
+ nl.ConvolutionalLayer(5, 6, 16),
134
+ nl.ReLU(),
135
+ nl.AvgPoolingLayer(),
136
+ nl.Flatten(),
137
+ nl.FullyConnectedLayer(n_inputs=400, n_outputs=120),
138
+ nl.ReLU(),
139
+ nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
140
+ nl.ReLU(),
141
+ nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
142
+ nl.Softmax(),
143
+ ])
144
+ loss_func = nl.CrossEntropyLoss()
145
+
146
+ learning_rate = 0.01
147
+ n_epochs = 20 # test acc at ~99% with AvgPooling
148
+ batchsize = 32
149
+
150
+ optimizer = nl.OptimizerADAM(loss_func, learning_rate)
151
+ log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
152
+
153
+ assert log['acc_train'][-1] > 0.95
154
+ #return log
155
+
156
+ if __name__ == '__main__':
157
+ # manual testing, ignored by pytest
158
+
159
+ #log = test_xor_classifier()
160
+ #log = test_mnist_fcn() # fast fully-connected network, more overfitting
161
+ log = test_mnist_lenet() # original LeNet CNN
162
+
163
+ plt.plot(log['loss_train'], label='training')
164
+ plt.plot(log['loss_valid'], label='validation')
165
+ plt.legend(loc='best')
166
+ plt.xlabel('epoch')
167
+ plt.ylabel('loss')
168
+ plt.grid()
169
+ plt.show()
170
+
171
+ plt.plot(log['acc_train'], label='training')
172
+ plt.plot(log['acc_valid'], label='validation')
173
+ plt.legend(loc='best')
174
+ plt.xlabel('epoch')
175
+ plt.ylabel('accuracy')
176
+ plt.grid()
177
+ plt.show()
@@ -1,2 +0,0 @@
1
- build
2
- twine
@@ -1,169 +0,0 @@
1
- import numpy as np
2
- import time
3
- import matplotlib.pyplot as plt
4
-
5
- import netlite as nl
6
-
7
- def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=10, batchsize=32):
8
- log = {}
9
- log['loss_train'] = []
10
- log['loss_valid'] = []
11
- log['acc_train'] = []
12
- log['acc_valid'] = []
13
- for epoch in range(n_epochs):
14
- start_time = time.time()
15
-
16
- loss_sum = 0
17
- n_correct_sum = 0
18
- for x_batch, y_batch in nl.batch_handler(X_train, y_train, batchsize=batchsize, shuffle=True):
19
- loss, metrics = optimizer.step(model, x_batch, y_batch)
20
- loss_sum += loss
21
- n_correct_sum += metrics['n_correct']
22
-
23
- end_time = time.time()
24
- elapsed_time = end_time - start_time
25
- print(f"runtime: {elapsed_time:.1f} sec")
26
-
27
- loss_train_mean = loss_sum / len(y_train)
28
- log['loss_train'].append(loss_train_mean)
29
- log['acc_train'].append(n_correct_sum / len(y_train))
30
-
31
- if len(X_valid) > 0: # if validation data is available
32
- loss_sum_valid, metrics = optimizer.step(model, X_valid, y_valid, forward_only=True)
33
- loss_valid_mean = loss_sum_valid / len(y_valid)
34
- log['loss_valid'].append(loss_valid_mean)
35
- log['acc_valid'].append(metrics['n_correct'] / len(y_valid))
36
- 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}')
37
- else:
38
- print(f'Epoch {epoch+1:3d} : loss_train {loss_train_mean:7.4f}, acc_train {log["acc_train"][-1]:5.3f}')
39
-
40
- return log
41
-
42
- if __name__ == '__main__':
43
- testcase = 'xor'
44
- #testcase = 'mnist_fcn' # fast fully-connected network, more overfitting
45
- testcase = 'mnist_lenet' # original LeNet CNN
46
-
47
- if testcase == 'xor':
48
-
49
- use_sigmoid = True
50
- if use_sigmoid:
51
- #np.random.seed(1)
52
- learning_rate = 2 # for Sigmoid activation function
53
-
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
- else:
61
- #np.random.seed(2)
62
- learning_rate = 0.1 # for ReLU activation function
63
-
64
- model = nl.NeuralNetwork([
65
- nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
66
- nl.LeakyReLU(),
67
- nl.FullyConnectedLayer(n_inputs=2, n_outputs=1),
68
- nl.LeakyReLU(),
69
- ])
70
-
71
- loss_func = nl.MseLoss()
72
-
73
- # x1 x2
74
- X_train = np.array((( 0, 0),
75
- ( 1, 0),
76
- ( 0, 1),
77
- ( 1, 1)))
78
-
79
- # desired output: logical XOR
80
- y_train = np.array((1,
81
- 0,
82
- 0,
83
- 1)).reshape((4,1))
84
-
85
- X_test = ()
86
- y_test = ()
87
-
88
- batchsize = 4
89
- n_epochs = 1000
90
- optim = 'sgd'
91
-
92
- elif testcase == 'mnist_fcn':
93
- X_train, y_train = nl.dataloader_mnist.load_train(num_images = 60000)
94
- X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 10000)
95
-
96
- model = nl.NeuralNetwork([
97
- nl.Flatten(), # convert image to vector
98
- nl.FullyConnectedLayer(n_inputs=32**2, n_outputs=100),
99
- nl.ReLU(),
100
- nl.FullyConnectedLayer(n_inputs=100, n_outputs=200),
101
- nl.ReLU(),
102
- nl.FullyConnectedLayer(n_inputs=200, n_outputs=10),
103
- nl.Softmax(),
104
- ])
105
-
106
- loss_func = nl.CrossEntropyLoss()
107
-
108
- learning_rate = 0.001
109
- n_epochs = 25
110
- batchsize = 100
111
- optim = 'adam'
112
-
113
- elif testcase == 'mnist_lenet':
114
- X_train, y_train = nl.dataloader_mnist.load_train(num_images = 60000)
115
- X_test, y_test = nl.dataloader_mnist.load_valid(num_images = 10000)
116
-
117
- # show some numbers
118
- #fig, ax = plt.subplots(1, 6, figsize=(6,1), dpi=100)
119
- #for axis, idx in zip(fig.axes, np.arange(0, 6)):
120
- # axis.imshow(X_train[idx, :, :, :], cmap='gray')
121
- # axis.axis('off')
122
- #plt.show()
123
-
124
- model = nl.NeuralNetwork([
125
- nl.ConvolutionalLayer(5, 1, 6),
126
- nl.ReLU(),
127
- nl.AvgPoolingLayer(),
128
- nl.ConvolutionalLayer(5, 6, 16),
129
- nl.ReLU(),
130
- nl.AvgPoolingLayer(),
131
- nl.Flatten(),
132
- nl.FullyConnectedLayer(n_inputs=400, n_outputs=120),
133
- nl.ReLU(),
134
- nl.FullyConnectedLayer(n_inputs=120, n_outputs=84),
135
- nl.ReLU(),
136
- nl.FullyConnectedLayer(n_inputs=84, n_outputs=10),
137
- nl.Softmax(),
138
- ])
139
- loss_func = nl.CrossEntropyLoss()
140
-
141
- learning_rate = 0.001
142
- n_epochs = 20 # test acc at ~99% with AvgPooling
143
- batchsize = 32
144
- optim = 'adam'
145
-
146
- if optim == 'sgd':
147
- optimizer = nl.OptimizerSGD(loss_func, learning_rate)
148
- elif optim == 'momentum':
149
- optimizer = nl.OptimizerMomentum(loss_func, learning_rate)
150
- elif optim == 'adam':
151
- optimizer = nl.OptimizerADAM(loss_func, learning_rate)
152
-
153
- log = train(model, optimizer, X_train, y_train, X_test, y_test, n_epochs, batchsize)
154
-
155
- plt.plot(log['loss_train'], label='training')
156
- plt.plot(log['loss_valid'], label='validation')
157
- plt.legend(loc='best')
158
- plt.xlabel('epoch')
159
- plt.ylabel('loss')
160
- plt.grid()
161
- plt.show()
162
-
163
- plt.plot(log['acc_train'], label='training')
164
- plt.plot(log['acc_valid'], label='validation')
165
- plt.legend(loc='best')
166
- plt.xlabel('epoch')
167
- plt.ylabel('accuracy')
168
- plt.grid()
169
- plt.show()
@@ -1,108 +0,0 @@
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}")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes