neurz 0.0.2__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.
neurz/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.2"
neurz/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
File without changes
Binary file
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
Binary file
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
neurz/cli.py ADDED
@@ -0,0 +1,94 @@
1
+ """Command line: ``neurz`` / ``nz``.
2
+
3
+ No arguments opens the window. Subcommands work in a terminal:
4
+
5
+ nz models list the models
6
+ nz run lstm [--random --seed 3] print every step of a run with its numbers
7
+ nz run cnn --sample vertical
8
+ nz concepts list every concept key
9
+ nz explain forget_gate --level math
10
+ nz update upgrade neurz with this Python's pip
11
+ nz -v | -V | --version
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import re
17
+ import subprocess
18
+ import sys
19
+
20
+ from . import __version__
21
+
22
+ VERSION_FLAGS = {"-v", "-V", "--version", "--Version", "-version", "--v", "--V"}
23
+
24
+
25
+ def _plain(s: str) -> str:
26
+ s = s.replace("<br>", "\n").replace("<sub>", "").replace("</sub>", "").replace("<sup>", "^").replace("</sup>", "")
27
+ return re.sub(r"<[^>]+>", "", s)
28
+
29
+
30
+ def main(argv: list[str] | None = None) -> int:
31
+ argv = list(sys.argv[1:] if argv is None else argv)
32
+ if any(a in VERSION_FLAGS for a in argv):
33
+ print(f"neurz {__version__}")
34
+ return 0
35
+ if not argv or argv[0] == "gui":
36
+ from .gui.app import run
37
+ return run()
38
+
39
+ from .core import data, glossary, models
40
+ from .core.i18n import phase
41
+ from .settings import system_lang
42
+
43
+ ap = argparse.ArgumentParser(prog="neurz", description="Educational RNN / LSTM / GRU / CNN visualiser")
44
+ ap.add_argument("--lang", choices=["tr", "en"], default=None)
45
+ sub = ap.add_subparsers(dest="cmd")
46
+ sub.add_parser("models")
47
+ r = sub.add_parser("run")
48
+ r.add_argument("model", choices=models.MODELS)
49
+ r.add_argument("--random", action="store_true", help="untrained random weights")
50
+ r.add_argument("--seed", type=int, default=7)
51
+ r.add_argument("--sample", choices=data.CNN_CLASSES, default="plus")
52
+ sub.add_parser("concepts")
53
+ e = sub.add_parser("explain")
54
+ e.add_argument("concept")
55
+ e.add_argument("--level", choices=glossary.LEVELS, default="detail")
56
+ sub.add_parser("update")
57
+ args = ap.parse_args(argv)
58
+ lang = args.lang or system_lang()
59
+
60
+ if args.cmd == "models":
61
+ for m in models.MODELS:
62
+ print(f"{m:5s} {_plain(glossary.get(m, lang)['title'])}")
63
+ return 0
64
+ if args.cmd == "run":
65
+ tr = models.build(args.model, trained=not args.random, seed=args.seed, sample=args.sample)
66
+ word = tr.meta.get("word")
67
+ for k, fr in enumerate(tr.frames, 1):
68
+ kw = {"t": max(0, fr.t), "r": fr.extra.get("r", 0), "c": fr.extra.get("c", 0),
69
+ "ch": word[fr.t] if word and fr.t >= 0 else "", "nx": word[fr.t + 1] if word and fr.t >= 0 else ""}
70
+ title = phase(lang, fr.phase, **kw)[0]
71
+ print(f"{k:3d} {_plain(title):32s} {fr.formula}")
72
+ return 0
73
+ if args.cmd == "concepts":
74
+ for k in glossary.keys():
75
+ print(f"{k:20s} {_plain(glossary.get(k, lang)['title'])}")
76
+ return 0
77
+ if args.cmd == "explain":
78
+ try:
79
+ g = glossary.get(args.concept, lang)
80
+ except KeyError:
81
+ print(f"unknown concept: {args.concept} (see: neurz concepts)", file=sys.stderr)
82
+ return 2
83
+ print(_plain(g["title"]))
84
+ print()
85
+ print(_plain(g[args.level]))
86
+ return 0
87
+ if args.cmd == "update":
88
+ return subprocess.call([sys.executable, "-m", "pip", "install", "-U", "neurz"])
89
+ ap.print_help()
90
+ return 0
91
+
92
+
93
+ if __name__ == "__main__":
94
+ raise SystemExit(main())
neurz/core/__init__.py ADDED
File without changes
neurz/core/data.py ADDED
@@ -0,0 +1,108 @@
1
+ """Sample inputs and stored weights.
2
+
3
+ Sequence models (RNN, LSTM, GRU) read the word "neurz" one letter at a time and
4
+ try to predict the next letter: n→e, e→u, u→r, r→z. Each letter enters as a
5
+ one-hot vector. The CNN looks at small 8×8 pictures of a vertical bar, a
6
+ horizontal bar or a plus sign.
7
+
8
+ Trained weights live in ``weights.json`` (made by ``tools/train_weights.py``);
9
+ "random" weights come from a seed so a student can compare an untrained network
10
+ with a trained one.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from functools import lru_cache
16
+ from importlib import resources
17
+
18
+ import numpy as np
19
+
20
+ VOCAB = ["n", "e", "u", "r", "z"]
21
+ WORD = "neurz"
22
+ HIDDEN = 4
23
+
24
+
25
+ def one_hot(ch: str) -> np.ndarray:
26
+ v = np.zeros(len(VOCAB))
27
+ v[VOCAB.index(ch)] = 1.0
28
+ return v
29
+
30
+
31
+ def sequence(word: str = WORD):
32
+ """Inputs (all letters but the last) and targets (all but the first)."""
33
+ xs = [one_hot(c) for c in word[:-1]]
34
+ ys = [VOCAB.index(c) for c in word[1:]]
35
+ return xs, ys
36
+
37
+
38
+ # ---------------------------------------------------------------- CNN images
39
+ CNN_CLASSES = ["vertical", "horizontal", "plus"]
40
+
41
+
42
+ def bar_image(kind: str, pos: int = 3) -> np.ndarray:
43
+ img = np.zeros((8, 8))
44
+ if kind in ("vertical", "plus"):
45
+ img[1:7, pos] = 1.0
46
+ if kind in ("horizontal", "plus"):
47
+ img[pos, 1:7] = 1.0
48
+ return img
49
+
50
+
51
+ CNN_SAMPLES = {
52
+ "vertical": bar_image("vertical", 3),
53
+ "horizontal": bar_image("horizontal", 4),
54
+ "plus": bar_image("plus", 3),
55
+ }
56
+
57
+ KERNELS = np.array([
58
+ [[-1.0, 2.0, -1.0], [-1.0, 2.0, -1.0], [-1.0, 2.0, -1.0]], # vertical-line detector
59
+ [[-1.0, -1.0, -1.0], [2.0, 2.0, 2.0], [-1.0, -1.0, -1.0]], # horizontal-line detector
60
+ ])
61
+
62
+
63
+ # ---------------------------------------------------------------- weights
64
+ @lru_cache(maxsize=1)
65
+ def _stored() -> dict:
66
+ text = resources.files("neurz.core").joinpath("weights.json").read_text(encoding="utf-8")
67
+ return json.loads(text)
68
+
69
+
70
+ def _shapes(model: str) -> dict[str, tuple[int, ...]]:
71
+ V, H = len(VOCAB), HIDDEN
72
+ if model == "rnn":
73
+ return {"W_xh": (H, V), "W_hh": (H, H), "b_h": (H,), "W_hy": (V, H), "b_y": (V,)}
74
+ if model == "lstm":
75
+ s = {}
76
+ for g in "figo":
77
+ s[f"W_{g}"] = (H, H + V)
78
+ s[f"b_{g}"] = (H,)
79
+ s.update({"W_hy": (V, H), "b_y": (V,)})
80
+ return s
81
+ if model == "gru":
82
+ s = {}
83
+ for g in "rzh":
84
+ s[f"W_{g}"] = (H, H + V)
85
+ s[f"b_{g}"] = (H,)
86
+ s.update({"W_hy": (V, H), "b_y": (V,)})
87
+ return s
88
+ if model == "cnn":
89
+ return {"W_d": (len(CNN_CLASSES), 18), "b_d": (len(CNN_CLASSES),)}
90
+ raise ValueError(model)
91
+
92
+
93
+ def random_weights(model: str, seed: int = 7) -> dict[str, np.ndarray]:
94
+ rng = np.random.default_rng(seed)
95
+ out = {}
96
+ for k, shp in _shapes(model).items():
97
+ out[k] = np.zeros(shp) if k.startswith("b") else rng.normal(0, 0.6, shp)
98
+ return out
99
+
100
+
101
+ def weights(model: str, trained: bool = True, seed: int = 7) -> dict[str, np.ndarray]:
102
+ if trained:
103
+ try:
104
+ raw = _stored()[model]
105
+ return {k: np.array(v, dtype=float) for k, v in raw.items()}
106
+ except (FileNotFoundError, KeyError):
107
+ pass
108
+ return random_weights(model, seed)