netlite 1.0.2__tar.gz → 1.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 (27) hide show
  1. {netlite-1.0.2 → netlite-1.0.4}/PKG-INFO +3 -3
  2. {netlite-1.0.2 → netlite-1.0.4}/README.md +1 -1
  3. {netlite-1.0.2 → netlite-1.0.4}/examples/netlite_example_fit_regression_line.py +2 -2
  4. {netlite-1.0.2 → netlite-1.0.4}/examples/netlite_example_xor_classifier.py +1 -1
  5. {netlite-1.0.2 → netlite-1.0.4}/package_upload.py +86 -77
  6. {netlite-1.0.2 → netlite-1.0.4}/pyproject.toml +1 -1
  7. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/neural_network.py +1 -1
  8. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/optimizer.py +14 -3
  9. netlite-1.0.4/tests/test_batch_handler.py +33 -0
  10. netlite-1.0.2/tests/test_netlite.py → netlite-1.0.4/tests/test_example_models.py +2 -2
  11. netlite-1.0.4/tests/test_neural_network.py +30 -0
  12. {netlite-1.0.2 → netlite-1.0.4}/.gitignore +0 -0
  13. {netlite-1.0.2 → netlite-1.0.4}/LICENSE +0 -0
  14. {netlite-1.0.2 → netlite-1.0.4}/examples/netlite_example_lenet_cifar10.py +0 -0
  15. {netlite-1.0.2 → netlite-1.0.4}/examples/netlite_example_lenet_mnist.py +0 -0
  16. {netlite-1.0.2 → netlite-1.0.4}/images/lenet_mnist_acc_curves.svg +0 -0
  17. {netlite-1.0.2 → netlite-1.0.4}/images/logo_netlite.png +0 -0
  18. {netlite-1.0.2 → netlite-1.0.4}/package_build.py +0 -0
  19. {netlite-1.0.2 → netlite-1.0.4}/package_run_tests.py +0 -0
  20. {netlite-1.0.2 → netlite-1.0.4}/requirements.txt +0 -0
  21. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/__init__.py +0 -0
  22. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/dataloader_cifar10.py +0 -0
  23. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/dataloader_mnist.py +0 -0
  24. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/layers.py +0 -0
  25. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/loss_functions.py +0 -0
  26. {netlite-1.0.2 → netlite-1.0.4}/src/netlite/numba_optional.py +0 -0
  27. {netlite-1.0.2 → netlite-1.0.4}/tests/test_convolution.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: netlite
3
- Version: 1.0.2
3
+ Version: 1.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
@@ -89,7 +89,7 @@ y_train = np.array((1,
89
89
  0,
90
90
  1)).reshape((4,1))
91
91
 
92
- optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
92
+ optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=8)
93
93
 
94
94
  log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
95
95
 
@@ -71,7 +71,7 @@ y_train = np.array((1,
71
71
  0,
72
72
  1)).reshape((4,1))
73
73
 
74
- optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
74
+ optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=8)
75
75
 
76
76
  log = train(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
77
77
 
@@ -36,13 +36,13 @@ y_train[3:5] -= 40 # outliers
36
36
  model1 = nl.NeuralNetwork([
37
37
  nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
38
38
  ])
39
- optimizer1 = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=0.0001)
39
+ optimizer1 = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=0.002)
40
40
  log1 = training_loop(model1, optimizer1, x_train, y_train)
41
41
 
42
42
  model2 = nl.NeuralNetwork([
43
43
  nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
44
44
  ])
45
- optimizer2 = nl.OptimizerSGD(loss_func=nl.HuberLoss(2.0), learning_rate=0.0001)
45
+ optimizer2 = nl.OptimizerSGD(loss_func=nl.HuberLoss(2.0), learning_rate=0.002)
46
46
  log2 = training_loop(model2, optimizer2, x_train, y_train)
47
47
 
48
48
  model1_out = model1.forward(x_train)
@@ -49,7 +49,7 @@ y_train = np.array((1,
49
49
  0,
50
50
  1)).reshape((4,1))
51
51
 
52
- optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=2)
52
+ optimizer = nl.OptimizerSGD(loss_func=nl.MseLoss(), learning_rate=8)
53
53
 
54
54
  log = training_loop(model, optimizer, X_train, y_train, n_epochs=500, batchsize=4)
55
55
 
@@ -1,77 +1,86 @@
1
- #!/usr/bin/env python
2
- import tomllib
3
- import requests
4
- from packaging.version import Version
5
- import sys
6
- import subprocess
7
-
8
- from package_run_tests import run_tests
9
- from package_build import build_package
10
-
11
- PACKAGE_NAME = "netlite"
12
-
13
- # Steps:
14
- # - run pytest
15
- # - build (with new release number)
16
- # - push to github (with release tag)
17
- # - upload to pipy
18
-
19
- def git_tag_and_push():
20
- # Check code is fully committed in git
21
- status = subprocess.run(
22
- ["git", "status", "--porcelain"],
23
- capture_output=True,
24
- text=True,
25
- check=True
26
- ).stdout.strip()
27
-
28
- if status:
29
- print("Error: Working tree is dirty. Commit or stash your changes first.")
30
- print(status)
31
- return False
32
-
33
- subprocess.run(['git', 'push']) # push commits
34
-
35
- # 1. Read local version from pyproject.toml
36
- with open("pyproject.toml", "rb") as f:
37
- pyproject = tomllib.load(f)
38
-
39
- local_version = pyproject["project"]["version"]
40
-
41
- # 2. Get latest version from PyPI
42
- #url = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
43
- #pypi_version = requests.get(url, timeout=10).json()["info"]["version"]
44
-
45
- # 3. Get latest git tag
46
- git_tag = subprocess.run(
47
- ["git", "describe", "--tags", "--abbrev=0"],
48
- capture_output=True,
49
- text=True,
50
- check=True
51
- ).stdout.strip()
52
- # strip leading "v" (v1.2.3 → 1.2.3)
53
- git_version = git_tag.lstrip("v")
54
-
55
- # 4. Compare
56
- print("version in pyproject.toml: ", local_version)
57
- print("version in git tag: ", git_version)
58
- #print("version on pypi.org: ", pypi_version)
59
- if Version(git_version) < Version(local_version):
60
- git_tag_new = 'v' + local_version
61
- print(f"Info: Updating git tag to '{git_tag_new}'")
62
- subprocess.run(['git', 'tag', git_tag_new])
63
- subprocess.run(['git', 'push', 'origin', git_tag_new]) # push new tag
64
-
65
- success = run_tests()
66
- if not success:
67
- sys.exit()
68
-
69
- success = build_package(require_new_version=True)
70
- if not success:
71
- sys.exit()
72
-
73
- success = git_tag_and_push()
74
- if not success:
75
- sys.exit()
76
-
77
- #subprocess.run(['twine', 'upload', 'dist/*'])
1
+ #!/usr/bin/env python
2
+ import tomllib
3
+ import requests
4
+ from packaging.version import Version
5
+ import sys
6
+ import subprocess
7
+
8
+ from package_run_tests import run_tests
9
+ from package_build import build_package
10
+
11
+ PACKAGE_NAME = "netlite"
12
+
13
+ # Steps:
14
+ # - run pytest
15
+ # - build (with new release number)
16
+ # - push to github (with release tag)
17
+ # - upload to pipy
18
+
19
+ def git_check_status():
20
+ # Check code is fully committed in git
21
+ status = subprocess.run(
22
+ ["git", "status", "--porcelain"],
23
+ capture_output=True,
24
+ text=True,
25
+ check=True
26
+ ).stdout.strip()
27
+
28
+ if status:
29
+ print("Error: Working tree is dirty. Commit or stash your changes first.")
30
+ print(status)
31
+ return False
32
+
33
+ return True
34
+
35
+ def git_tag_and_push():
36
+ subprocess.run(['git', 'push']) # push commits
37
+
38
+ # 1. Read local version from pyproject.toml
39
+ with open("pyproject.toml", "rb") as f:
40
+ pyproject = tomllib.load(f)
41
+
42
+ local_version = pyproject["project"]["version"]
43
+
44
+ # 2. Get latest version from PyPI
45
+ #url = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
46
+ #pypi_version = requests.get(url, timeout=10).json()["info"]["version"]
47
+
48
+ # 3. Get latest git tag
49
+ git_tag = subprocess.run(
50
+ ["git", "describe", "--tags", "--abbrev=0"],
51
+ capture_output=True,
52
+ text=True,
53
+ check=True
54
+ ).stdout.strip()
55
+ # strip leading "v" (v1.2.3 → 1.2.3)
56
+ git_version = git_tag.lstrip("v")
57
+
58
+ # 4. Compare
59
+ print("version in pyproject.toml: ", local_version)
60
+ print("version in git tag: ", git_version)
61
+ #print("version on pypi.org: ", pypi_version)
62
+ if Version(git_version) < Version(local_version):
63
+ git_tag_new = 'v' + local_version
64
+ print(f"Info: Updating git tag to '{git_tag_new}'")
65
+ subprocess.run(['git', 'tag', git_tag_new])
66
+ subprocess.run(['git', 'push', 'origin', git_tag_new]) # push new tag
67
+
68
+ return True
69
+
70
+ success = git_check_status()
71
+ if not success:
72
+ sys.exit()
73
+
74
+ success = run_tests()
75
+ if not success:
76
+ sys.exit()
77
+
78
+ success = build_package(require_new_version=True)
79
+ if not success:
80
+ sys.exit()
81
+
82
+ success = git_tag_and_push()
83
+ if not success:
84
+ sys.exit()
85
+
86
+ subprocess.run(['twine', 'upload', 'dist/*'])
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "netlite"
7
- version = "1.0.2"
7
+ version = "1.0.4"
8
8
  authors = [
9
9
  { name="Hanno Homann", email="hanno.homann@example.com" },
10
10
  ]
@@ -62,4 +62,4 @@ class NeuralNetwork():
62
62
  weights = layer.get_weights()
63
63
  for key in weights:
64
64
  assert key in loaded_params[i].keys(), f'Error: Key {key} no found in layer {i} of file {filename}.'
65
- weights[key] = loaded_params[i][key]
65
+ weights[key][:] = loaded_params[i][key]
@@ -26,7 +26,11 @@ class OptimizerSGD():
26
26
  return loss.sum(), metrics
27
27
 
28
28
  # backward pass
29
- loss_gradient = self.loss_func.backward(y_model, y_true)
29
+ # Loss functions return the gradient of the summed loss; divide by the
30
+ # batch size so that the update follows the gradient of the mean loss
31
+ # and the learning rate does not depend on the batch size.
32
+ batch_size = len(X)
33
+ loss_gradient = self.loss_func.backward(y_model, y_true) / batch_size
30
34
 
31
35
  model.backward(loss_gradient, use_logits)
32
36
 
@@ -124,14 +128,21 @@ class OptimizerADAM(OptimizerSGD):
124
128
 
125
129
  layer_weights[key] -= self.learning_rate / (np.sqrt(self.v[i][key]) + self.eps) * self.m[i][key]
126
130
 
127
- def batch_handler(X, y, batchsize, shuffle=False):
131
+ def batch_handler(X, y, batchsize, shuffle=False, drop_last=False):
132
+ '''Iterate over (X, y) in mini-batches.
133
+
134
+ By default every sample is used once per pass: if len(X) is not a multiple
135
+ of batchsize, the last batch is smaller. Set drop_last=True to skip that
136
+ incomplete batch and only yield batches of exactly batchsize samples.
137
+ '''
128
138
  assert len(X) == len(y), f'Number of data {len(X)} does not match number of labels {len(y)}'
129
139
  batchsize = min(batchsize, len(y))
130
140
 
131
141
  if shuffle:
132
142
  idxs = np.random.permutation((len(y)))
133
143
 
134
- for start_idx in range(0, len(X) - batchsize + 1, batchsize):
144
+ end = len(X) - batchsize + 1 if drop_last else len(X)
145
+ for start_idx in range(0, end, batchsize):
135
146
  if shuffle:
136
147
  batch = idxs[start_idx:start_idx + batchsize]
137
148
  else:
@@ -0,0 +1,33 @@
1
+ import numpy as np
2
+
3
+ # add parent folder with netlite source to path
4
+ import os
5
+ import sys
6
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
7
+ sys.path.insert(0, parent_dir)
8
+ import netlite as nl
9
+
10
+ def test_batch_handler_keeps_last_batch():
11
+ X = np.arange(10).reshape(10, 1)
12
+ y = np.arange(10)
13
+ batch_sizes = [len(yb) for _, yb in nl.batch_handler(X, y, batchsize=4)]
14
+ assert batch_sizes == [4, 4, 2]
15
+
16
+ def test_batch_handler_shuffle_uses_every_sample_once():
17
+ X = np.arange(10).reshape(10, 1)
18
+ y = np.arange(10)
19
+ seen = np.concatenate([yb for _, yb in nl.batch_handler(X, y, batchsize=4, shuffle=True)])
20
+ assert sorted(seen) == list(range(10))
21
+
22
+ def test_batch_handler_drop_last():
23
+ X = np.arange(10).reshape(10, 1)
24
+ y = np.arange(10)
25
+ batch_sizes = [len(yb) for _, yb in nl.batch_handler(X, y, batchsize=4, drop_last=True)]
26
+ assert batch_sizes == [4, 4]
27
+
28
+ def test_batch_handler_exact_multiple():
29
+ X = np.arange(8).reshape(8, 1)
30
+ y = np.arange(8)
31
+ for drop_last in (False, True):
32
+ batch_sizes = [len(yb) for _, yb in nl.batch_handler(X, y, batchsize=4, drop_last=drop_last)]
33
+ assert batch_sizes == [4, 4]
@@ -52,7 +52,7 @@ def train(model, optimizer, X_train, y_train, X_valid=(), y_valid=(), n_epochs=1
52
52
  def test_xor_classifier():
53
53
  use_sigmoid = True
54
54
  if use_sigmoid:
55
- learning_rate = 2 # for Sigmoid activation function
55
+ learning_rate = 8 # for Sigmoid activation function
56
56
 
57
57
  model = nl.NeuralNetwork([
58
58
  nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
@@ -62,7 +62,7 @@ def test_xor_classifier():
62
62
  ])
63
63
  else:
64
64
  # LeakyReLU - does not always converge
65
- learning_rate = 0.1 # for ReLU activation function
65
+ learning_rate = 0.4 # for ReLU activation function
66
66
 
67
67
  model = nl.NeuralNetwork([
68
68
  nl.FullyConnectedLayer(n_inputs=2, n_outputs=2),
@@ -0,0 +1,30 @@
1
+ # add parent folder with netlite source to path
2
+ import os
3
+ import sys
4
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))
5
+ sys.path.insert(0, parent_dir)
6
+
7
+ import netlite as nl
8
+
9
+ def test_save_and_load():
10
+ model = nl.NeuralNetwork([
11
+ nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
12
+ ])
13
+
14
+ const1 = 3.
15
+ const2 = 4.
16
+ model.layers[0].weights[0,0] = const1
17
+ model.layers[0].bias[0] = const2
18
+
19
+ filename = 'pytest_params.npy'
20
+ model.save(filename)
21
+
22
+ model2 = nl.NeuralNetwork([
23
+ nl.FullyConnectedLayer(n_inputs=1, n_outputs=1),
24
+ ])
25
+ model2.load(filename)
26
+ os.remove(filename)
27
+
28
+ assert model2.layers[0].weights[0,0] == const1
29
+ assert model2.layers[0].bias[0] == const2
30
+
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes