nn3d 0.1.0__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.
- nn3d/__init__.py +133 -0
- nn3d/keras_adapter.py +360 -0
- nn3d/monitor.py +98 -0
- nn3d/schema.py +199 -0
- nn3d/server.py +235 -0
- nn3d/static/index.html +3955 -0
- nn3d-0.1.0.dist-info/METADATA +324 -0
- nn3d-0.1.0.dist-info/RECORD +10 -0
- nn3d-0.1.0.dist-info/WHEEL +4 -0
- nn3d-0.1.0.dist-info/licenses/LICENSE +179 -0
nn3d/__init__.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""nn3d - sinir aglarini tarayicida canli 3D olarak izle.
|
|
2
|
+
|
|
3
|
+
Hizli baslangic (Keras):
|
|
4
|
+
|
|
5
|
+
import nn3d
|
|
6
|
+
|
|
7
|
+
view = nn3d.show(model, input_labels=ozellik_adlari) # tarayici acilir
|
|
8
|
+
model.fit(X, y, callbacks=[nn3d.Monitor(X[:1], every=20)])
|
|
9
|
+
|
|
10
|
+
Notebook'ta calisiyorsan hicbir sey yapman gerekmez; sunucu cekirdek acik
|
|
11
|
+
kaldigi surece yasar. Duz bir .py betiginde betik bitince surec de biter,
|
|
12
|
+
o yuzden sonunda `view.wait()` cagir.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Any, Dict, Optional, Sequence
|
|
18
|
+
|
|
19
|
+
from . import schema
|
|
20
|
+
from .server import Server
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = ["show", "Monitor", "View", "Server", "schema"]
|
|
24
|
+
|
|
25
|
+
_active: Optional["View"] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class View:
|
|
29
|
+
"""Acik bir gorsellestirme oturumu: sunucu + aktivasyon muslugu."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
model: Any,
|
|
34
|
+
*,
|
|
35
|
+
name: Optional[str] = None,
|
|
36
|
+
input_labels: Optional[Sequence[str]] = None,
|
|
37
|
+
output_labels: Optional[Sequence[str]] = None,
|
|
38
|
+
max_neurons: int = schema.DEFAULT_MAX_NEURONS,
|
|
39
|
+
port: int = 8092,
|
|
40
|
+
):
|
|
41
|
+
from .keras_adapter import ActivationTap, build_graph
|
|
42
|
+
|
|
43
|
+
self.model = model
|
|
44
|
+
self.graph = build_graph(
|
|
45
|
+
model,
|
|
46
|
+
name=name,
|
|
47
|
+
input_labels=input_labels,
|
|
48
|
+
output_labels=output_labels,
|
|
49
|
+
max_neurons=max_neurons,
|
|
50
|
+
)
|
|
51
|
+
self.tap = ActivationTap(model, max_neurons=max_neurons)
|
|
52
|
+
self.server = Server(self.graph, port=port)
|
|
53
|
+
self._step = 0
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def url(self) -> str:
|
|
57
|
+
return self.server.url
|
|
58
|
+
|
|
59
|
+
def update(
|
|
60
|
+
self,
|
|
61
|
+
x: Any,
|
|
62
|
+
*,
|
|
63
|
+
metrics: Optional[Dict[str, float]] = None,
|
|
64
|
+
epoch: Optional[int] = None,
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Bir ornegi ileri yayar ve o anki aktivasyonlari tarayiciya yollar."""
|
|
67
|
+
acts = self.tap.read(x)
|
|
68
|
+
self.server.push(schema.frame(self._step, acts, epoch=epoch, metrics=metrics))
|
|
69
|
+
self._step += 1
|
|
70
|
+
|
|
71
|
+
def open_browser(self) -> None:
|
|
72
|
+
self.server.open_browser()
|
|
73
|
+
|
|
74
|
+
def wait(self) -> None:
|
|
75
|
+
self.server.wait()
|
|
76
|
+
|
|
77
|
+
def close(self) -> None:
|
|
78
|
+
self.server.close()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def show(
|
|
82
|
+
model: Any,
|
|
83
|
+
*,
|
|
84
|
+
sample: Any = None,
|
|
85
|
+
input_labels: Optional[Sequence[str]] = None,
|
|
86
|
+
output_labels: Optional[Sequence[str]] = None,
|
|
87
|
+
name: Optional[str] = None,
|
|
88
|
+
max_neurons: int = schema.DEFAULT_MAX_NEURONS,
|
|
89
|
+
port: int = 8092,
|
|
90
|
+
open_browser: bool = True,
|
|
91
|
+
) -> View:
|
|
92
|
+
"""Modeli cizer ve tarayiciyi acar.
|
|
93
|
+
|
|
94
|
+
sample verilirse ilk kare de hemen gonderilir, yani ekran bos kalmaz.
|
|
95
|
+
"""
|
|
96
|
+
global _active
|
|
97
|
+
if _active is not None:
|
|
98
|
+
_active.close()
|
|
99
|
+
view = View(
|
|
100
|
+
model,
|
|
101
|
+
name=name,
|
|
102
|
+
input_labels=input_labels,
|
|
103
|
+
output_labels=output_labels,
|
|
104
|
+
max_neurons=max_neurons,
|
|
105
|
+
port=port,
|
|
106
|
+
)
|
|
107
|
+
_active = view
|
|
108
|
+
if sample is not None:
|
|
109
|
+
view.update(sample)
|
|
110
|
+
if open_browser:
|
|
111
|
+
view.open_browser()
|
|
112
|
+
print(f"[nn3d] {view.url} ({view.graph['totalParams']:,} parametre)")
|
|
113
|
+
return view
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def wait() -> None:
|
|
117
|
+
"""Acik oturumu ayakta tutar (duz .py betikleri icin)."""
|
|
118
|
+
if _active is None:
|
|
119
|
+
raise RuntimeError("acik bir nn3d oturumu yok - once nn3d.show(model) cagir")
|
|
120
|
+
_active.wait()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def __getattr__(name: str) -> Any:
|
|
124
|
+
"""nn3d.Monitor'a ilk erisimde keras'i tembel yukler (PEP 562).
|
|
125
|
+
|
|
126
|
+
Boylece `import nn3d` Keras kurulu olmayan bir ortamda da calisir; sema ve
|
|
127
|
+
sunucu baska cerceveler icin tek basina kullanilabilir kalir.
|
|
128
|
+
"""
|
|
129
|
+
if name == "Monitor":
|
|
130
|
+
from .monitor import Monitor
|
|
131
|
+
|
|
132
|
+
return Monitor
|
|
133
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
nn3d/keras_adapter.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Keras 3 / TensorFlow modellerini nn3d semasina cevirir.
|
|
2
|
+
|
|
3
|
+
Iki is yapar:
|
|
4
|
+
build_graph(model) -> agin yapisi (bir kez)
|
|
5
|
+
ActivationTap(model).read(x) -> o anki aktivasyonlar (her adimda)
|
|
6
|
+
|
|
7
|
+
Tasarim notu -- SANALLASTIRMA:
|
|
8
|
+
Bir Dense(3072) katmanini 3072 nokta olarak cizmek hem okunmaz hem de onceki
|
|
9
|
+
768'lik katmanla arasinda 2.3 milyon kenar demektir; tarayici olur. Bu yuzden
|
|
10
|
+
her katmandan esit araliklarla `max_neurons` kadar TEMSILCI noron secilir ve
|
|
11
|
+
hem aktivasyonlar hem agirliklar ayni indislere gore kirpilir. Boylece ekranda
|
|
12
|
+
gordugun her nokta ve her cizgi GERCEK bir noron/agirliktir -- uydurma degil,
|
|
13
|
+
sadece bir alt kume.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from . import schema
|
|
23
|
+
|
|
24
|
+
# Kendi agirligi olmayan, girisi aynen (ya da olcekleyerek) geciren katmanlar.
|
|
25
|
+
# Bunlar ince sutunlar olarak cizilir ve noron i -> noron i duz baglanir.
|
|
26
|
+
_PASSTHROUGH = {
|
|
27
|
+
"Dropout", "SpatialDropout1D", "SpatialDropout2D", "GaussianDropout",
|
|
28
|
+
"BatchNormalization", "LayerNormalization", "GroupNormalization",
|
|
29
|
+
"Activation", "ReLU", "LeakyReLU", "ELU", "PReLU", "Softmax",
|
|
30
|
+
"MaxPooling1D", "MaxPooling2D", "MaxPooling3D",
|
|
31
|
+
"AveragePooling1D", "AveragePooling2D", "AveragePooling3D",
|
|
32
|
+
"GlobalMaxPooling2D", "GlobalAveragePooling2D",
|
|
33
|
+
"ZeroPadding2D", "Cropping2D", "UpSampling2D",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_CONV = {"Conv1D", "Conv2D", "Conv3D", "SeparableConv2D", "DepthwiseConv2D"}
|
|
37
|
+
_DECONV = {"Conv2DTranspose", "Conv1DTranspose", "Conv3DTranspose"}
|
|
38
|
+
_RNN = {"LSTM", "GRU", "SimpleRNN", "Bidirectional", "ConvLSTM2D"}
|
|
39
|
+
_RESHAPE = {"Flatten", "Reshape", "Permute", "RepeatVector"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _kind(layer: Any) -> str:
|
|
43
|
+
cls = type(layer).__name__
|
|
44
|
+
if cls in _PASSTHROUGH:
|
|
45
|
+
return "passthrough"
|
|
46
|
+
if cls in _CONV or cls in _DECONV:
|
|
47
|
+
return "conv"
|
|
48
|
+
if cls in _RNN:
|
|
49
|
+
return "rnn"
|
|
50
|
+
if cls in _RESHAPE:
|
|
51
|
+
return "reshape"
|
|
52
|
+
return "dense"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _activation_name(layer: Any) -> Optional[str]:
|
|
56
|
+
"""Kartin ucuncu satirinda kirmizi ile yazacak [ReLU] etiketi."""
|
|
57
|
+
cls = type(layer).__name__
|
|
58
|
+
if cls in ("ReLU", "LeakyReLU", "ELU", "PReLU", "Softmax"):
|
|
59
|
+
return cls
|
|
60
|
+
act = getattr(layer, "activation", None)
|
|
61
|
+
if act is None:
|
|
62
|
+
return None
|
|
63
|
+
name = getattr(act, "__name__", None) or str(act)
|
|
64
|
+
if name in ("linear", "None"):
|
|
65
|
+
return None
|
|
66
|
+
# relu -> ReLU, softmax -> Softmax, tanh -> Tanh
|
|
67
|
+
special = {"relu": "ReLU", "elu": "ELU", "selu": "SELU", "gelu": "GELU",
|
|
68
|
+
"prelu": "PReLU", "silu": "SiLU"}
|
|
69
|
+
return special.get(name, name.capitalize())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _out_shape(layer: Any) -> Tuple[Optional[int], ...]:
|
|
73
|
+
try:
|
|
74
|
+
return tuple(layer.output.shape)
|
|
75
|
+
except Exception:
|
|
76
|
+
return (None,)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _display_size(layer: Any) -> int:
|
|
80
|
+
"""Kartta yazan ve nokta sayisini belirleyen 'genislik'.
|
|
81
|
+
|
|
82
|
+
Her zaman SON eksen. Keras channels-last oldugu icin son eksen daima
|
|
83
|
+
ozellik/kanal eksenidir; onceki eksenler uzamsal ya da zamansaldir ve
|
|
84
|
+
kartta metin olarak gosterilir.
|
|
85
|
+
|
|
86
|
+
Dense(256) (None, 256) -> 256
|
|
87
|
+
Conv2D(32) (None, 26, 26, 32) -> 32
|
|
88
|
+
BatchNorm (conv sonrasi)(None, 26, 26, 32) -> 32
|
|
89
|
+
LSTM(64, ret_seq=True) (None, 60, 64) -> 64
|
|
90
|
+
Flatten (None, 1600) -> 1600
|
|
91
|
+
|
|
92
|
+
Onceki surumde yalnizca Conv katmanlarina bu kural uygulaniyordu; conv
|
|
93
|
+
sonrasi BatchNorm/MaxPooling/LeakyReLU duzlestirilmis boyutu (21632)
|
|
94
|
+
bildiriyor, bu da aktivasyon vektoru ile nokta sayisini uyumsuz
|
|
95
|
+
birakiyordu.
|
|
96
|
+
"""
|
|
97
|
+
shape = _out_shape(layer)
|
|
98
|
+
if len(shape) <= 1:
|
|
99
|
+
return 1
|
|
100
|
+
return int(shape[-1] or 1)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _shape_text(layer: Any) -> Optional[str]:
|
|
104
|
+
shape = _out_shape(layer)
|
|
105
|
+
dims = [s for s in shape[1:] if s is not None]
|
|
106
|
+
if len(dims) >= 2:
|
|
107
|
+
return "x".join(str(d) for d in dims)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _input_shape(model: Any) -> Tuple[List[int], int]:
|
|
112
|
+
"""Giris katmaninin (boyutlar, cizilecek noron sayisi) ikilisi.
|
|
113
|
+
|
|
114
|
+
Burada _display_size'in "son eksen" kurali BILEREK uygulanmiyor: bir
|
|
115
|
+
goruntu girisi icin son eksen kanal sayisidir (28x28x1 -> 1) ve tek bir
|
|
116
|
+
nokta cizmek anlamsiz olur. Giris ham veridir, ozellik degil; bu yuzden
|
|
117
|
+
duzlestirip (784) sanallastiriyoruz. Gercek sekil kartta metin olarak
|
|
118
|
+
zaten gorunuyor.
|
|
119
|
+
"""
|
|
120
|
+
if not getattr(model, "inputs", None):
|
|
121
|
+
return [], 1
|
|
122
|
+
dims = [int(s) for s in tuple(model.inputs[0].shape)[1:] if s]
|
|
123
|
+
if not dims:
|
|
124
|
+
return [], 1
|
|
125
|
+
return dims, int(np.prod(dims))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _pick(n: int, k: int) -> np.ndarray:
|
|
129
|
+
"""n elemandan esit araliklarla k temsilci indis secer."""
|
|
130
|
+
if n <= k:
|
|
131
|
+
return np.arange(n)
|
|
132
|
+
return np.unique(np.linspace(0, n - 1, k).round().astype(int))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _weight_matrix(layer: Any) -> Optional[np.ndarray]:
|
|
136
|
+
"""Katmanin agirligini (giris_birimi, cikis_birimi) matrisine indirger.
|
|
137
|
+
|
|
138
|
+
Amac gorsel: iki noron arasindaki baglantinin isareti ve siddeti. Cok
|
|
139
|
+
boyutlu cekirdekler bu iki boyuta ozetlenir.
|
|
140
|
+
"""
|
|
141
|
+
ws = layer.get_weights()
|
|
142
|
+
if not ws:
|
|
143
|
+
return None
|
|
144
|
+
k = np.asarray(ws[0], dtype=np.float32)
|
|
145
|
+
cls = type(layer).__name__
|
|
146
|
+
|
|
147
|
+
if k.ndim == 2:
|
|
148
|
+
if cls in ("LSTM", "GRU"):
|
|
149
|
+
# kernel: (giris, kapi_sayisi * birim). Kapilar uzerinden ortalama.
|
|
150
|
+
gates = 4 if cls == "LSTM" else 3
|
|
151
|
+
if k.shape[1] % gates == 0:
|
|
152
|
+
units = k.shape[1] // gates
|
|
153
|
+
return k.reshape(k.shape[0], gates, units).mean(axis=1)
|
|
154
|
+
return k
|
|
155
|
+
|
|
156
|
+
if k.ndim >= 3:
|
|
157
|
+
# Konvolusyon: uzamsal eksenler uzerinde topla -> (giris_k, cikis_k)
|
|
158
|
+
spatial = tuple(range(k.ndim - 2))
|
|
159
|
+
m = k.sum(axis=spatial)
|
|
160
|
+
if cls in _DECONV:
|
|
161
|
+
# Conv2DTranspose cekirdegi (kh, kw, filtre, giris_kanali) seklinde
|
|
162
|
+
m = m.T
|
|
163
|
+
return m
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def build_graph(
|
|
168
|
+
model: Any,
|
|
169
|
+
*,
|
|
170
|
+
name: Optional[str] = None,
|
|
171
|
+
input_labels: Optional[Sequence[str]] = None,
|
|
172
|
+
output_labels: Optional[Sequence[str]] = None,
|
|
173
|
+
max_neurons: int = schema.DEFAULT_MAX_NEURONS,
|
|
174
|
+
max_edges_per_pair: int = 4096,
|
|
175
|
+
) -> Dict[str, Any]:
|
|
176
|
+
"""Keras modelini ciziciye gonderilecek grafige cevirir."""
|
|
177
|
+
layers: List[Dict[str, Any]] = []
|
|
178
|
+
edges: List[Dict[str, Any]] = []
|
|
179
|
+
picks: Dict[str, np.ndarray] = {}
|
|
180
|
+
|
|
181
|
+
# --- giris katmani (Keras'ta Sequential'da gorunmez, kendimiz uyduruyoruz)
|
|
182
|
+
in_dims, in_size = _input_shape(model)
|
|
183
|
+
in_pick = _pick(in_size, max_neurons)
|
|
184
|
+
picks["__input__"] = in_pick
|
|
185
|
+
labels = None
|
|
186
|
+
if input_labels is not None:
|
|
187
|
+
lab = list(input_labels)
|
|
188
|
+
labels = [lab[i] if i < len(lab) else f"in[{i}]" for i in in_pick]
|
|
189
|
+
layers.append(schema.layer(
|
|
190
|
+
"__input__", "Input", "input", in_size,
|
|
191
|
+
shape_text="x".join(str(d) for d in in_dims) if len(in_dims) > 1 else None,
|
|
192
|
+
neuron_labels=labels, max_neurons=max_neurons,
|
|
193
|
+
))
|
|
194
|
+
|
|
195
|
+
prev_id = "__input__"
|
|
196
|
+
prev_size = in_size
|
|
197
|
+
keras_layers = list(model.layers)
|
|
198
|
+
|
|
199
|
+
for i, kl in enumerate(keras_layers):
|
|
200
|
+
kind = _kind(kl)
|
|
201
|
+
size = _display_size(kl)
|
|
202
|
+
lid = kl.name
|
|
203
|
+
is_last = i == len(keras_layers) - 1
|
|
204
|
+
|
|
205
|
+
sel = _pick(size, max_neurons)
|
|
206
|
+
picks[lid] = sel
|
|
207
|
+
|
|
208
|
+
nlabels = None
|
|
209
|
+
if is_last and output_labels is not None:
|
|
210
|
+
ol = list(output_labels)
|
|
211
|
+
nlabels = [ol[j] if j < len(ol) else f"out[{j}]" for j in sel]
|
|
212
|
+
|
|
213
|
+
layers.append(schema.layer(
|
|
214
|
+
lid,
|
|
215
|
+
_pretty_label(kl),
|
|
216
|
+
"output" if is_last else kind,
|
|
217
|
+
size,
|
|
218
|
+
activation=_activation_name(kl),
|
|
219
|
+
shape_text=_shape_text(kl),
|
|
220
|
+
neuron_labels=nlabels,
|
|
221
|
+
max_neurons=max_neurons,
|
|
222
|
+
params=int(kl.count_params()),
|
|
223
|
+
))
|
|
224
|
+
|
|
225
|
+
# --- kenar: onceki katmandan buraya
|
|
226
|
+
W = _weight_matrix(kl)
|
|
227
|
+
src_pick = picks[prev_id]
|
|
228
|
+
if W is not None and W.shape[0] == prev_size:
|
|
229
|
+
sub = W[np.ix_(src_pick, sel)]
|
|
230
|
+
sub = _thin(sub, max_edges_per_pair)
|
|
231
|
+
edges.append(schema.edge(
|
|
232
|
+
prev_id, lid, kind="dense",
|
|
233
|
+
shape=sub.shape, weights=sub.ravel(order="C"),
|
|
234
|
+
))
|
|
235
|
+
elif kind == "passthrough" and size == prev_size:
|
|
236
|
+
edges.append(schema.edge(prev_id, lid, kind="identity"))
|
|
237
|
+
else:
|
|
238
|
+
# Flatten/Reshape ya da boyutu tutmayan agirlik: yapisal baglanti
|
|
239
|
+
edges.append(schema.edge(prev_id, lid, kind="reshape"))
|
|
240
|
+
|
|
241
|
+
# RNN'in kendine donen baglantisi -- gorselde mor halkalar
|
|
242
|
+
if kind == "rnn":
|
|
243
|
+
edges.append(schema.edge(lid, lid, kind="recurrent"))
|
|
244
|
+
|
|
245
|
+
prev_id, prev_size = lid, size
|
|
246
|
+
|
|
247
|
+
return schema.graph(
|
|
248
|
+
name or getattr(model, "name", None) or "model",
|
|
249
|
+
layers, edges,
|
|
250
|
+
framework="keras",
|
|
251
|
+
totalParams=int(model.count_params()),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# Uzun sinif adlari kartlari sisirip komsulariyla cakistiriyor. Kisaltmalar
|
|
256
|
+
# yaygin ve tanidik oldugu icin bilgi kaybi yok.
|
|
257
|
+
_SHORT = {
|
|
258
|
+
"BatchNormalization": "BatchNorm",
|
|
259
|
+
"LayerNormalization": "LayerNorm",
|
|
260
|
+
"GroupNormalization": "GroupNorm",
|
|
261
|
+
"MaxPooling1D": "MaxPool1D", "MaxPooling2D": "MaxPool2D", "MaxPooling3D": "MaxPool3D",
|
|
262
|
+
"AveragePooling1D": "AvgPool1D", "AveragePooling2D": "AvgPool2D",
|
|
263
|
+
"GlobalMaxPooling2D": "GlobalMaxPool",
|
|
264
|
+
"GlobalAveragePooling2D": "GlobalAvgPool",
|
|
265
|
+
"SpatialDropout2D": "SpDropout2D",
|
|
266
|
+
"Conv2DTranspose": "Conv2DT", "Conv1DTranspose": "Conv1DT",
|
|
267
|
+
"SeparableConv2D": "SepConv2D",
|
|
268
|
+
"Bidirectional": "BiRNN",
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _pretty_label(layer: Any) -> str:
|
|
273
|
+
"""dense_3 -> "Dense 3" gibi okunakli, KISA bir baslik."""
|
|
274
|
+
cls = type(layer).__name__
|
|
275
|
+
short = _SHORT.get(cls, cls)
|
|
276
|
+
raw = layer.name
|
|
277
|
+
suffix = raw.rsplit("_", 1)[-1]
|
|
278
|
+
if suffix.isdigit():
|
|
279
|
+
return f"{short} {suffix}"
|
|
280
|
+
# Keras varsayilan adi sinif adinin snake_case hali ("batch_normalization").
|
|
281
|
+
# Alt tireleri atmadan karsilastirinca hicbir zaman eslesmiyor ve kart
|
|
282
|
+
# "BatchNormalization (batch_normalization)" gibi ise yaramaz sekilde
|
|
283
|
+
# uzuyordu.
|
|
284
|
+
if raw.replace("_", "").lower().startswith(cls.lower()):
|
|
285
|
+
return short
|
|
286
|
+
return f"{short} ({raw})"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _thin(m: np.ndarray, budget: int) -> np.ndarray:
|
|
290
|
+
"""Kenar sayisi butceyi asiyorsa en zayif agirliklari sifirla.
|
|
291
|
+
|
|
292
|
+
Matrisin sekli korunur (cizici sekle guveniyor); sadece degerler sifirlanir
|
|
293
|
+
ve cizici sifir agirlikli kenari hic cizmez.
|
|
294
|
+
"""
|
|
295
|
+
total = m.size
|
|
296
|
+
if total <= budget:
|
|
297
|
+
return m
|
|
298
|
+
flat = np.abs(m).ravel()
|
|
299
|
+
thresh = np.partition(flat, total - budget)[total - budget]
|
|
300
|
+
out = m.copy()
|
|
301
|
+
out[np.abs(out) < thresh] = 0.0
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class ActivationTap:
|
|
306
|
+
"""Modelin ara katman ciktilarini okur.
|
|
307
|
+
|
|
308
|
+
Egitim sirasinda her cagrida yeni bir Model kurmak cok pahali olurdu;
|
|
309
|
+
probe modeli bir kez kurulur ve tekrar tekrar kullanilir.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
def __init__(self, model: Any, *, max_neurons: int = schema.DEFAULT_MAX_NEURONS):
|
|
313
|
+
import keras
|
|
314
|
+
|
|
315
|
+
self.model = model
|
|
316
|
+
self.max_neurons = max_neurons
|
|
317
|
+
self.ids = ["__input__"] + [l.name for l in model.layers]
|
|
318
|
+
self._picks: Dict[str, np.ndarray] = {}
|
|
319
|
+
|
|
320
|
+
_, in_size = _input_shape(model)
|
|
321
|
+
self._picks["__input__"] = _pick(in_size, max_neurons)
|
|
322
|
+
for l in model.layers:
|
|
323
|
+
self._picks[l.name] = _pick(_display_size(l), max_neurons)
|
|
324
|
+
|
|
325
|
+
self._probe = keras.Model(
|
|
326
|
+
inputs=model.inputs,
|
|
327
|
+
outputs=[l.output for l in model.layers],
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
def read(self, x: Any) -> Dict[str, np.ndarray]:
|
|
331
|
+
"""Tek bir ornek (ya da batch) icin katman aktivasyonlarini dondurur."""
|
|
332
|
+
x = np.asarray(x, dtype="float32")
|
|
333
|
+
if x.shape[1:] != tuple(s for s in self.model.inputs[0].shape[1:]):
|
|
334
|
+
x = x.reshape((-1,) + tuple(int(s) for s in self.model.inputs[0].shape[1:]))
|
|
335
|
+
outs = self._probe.predict(x, verbose=0)
|
|
336
|
+
if not isinstance(outs, (list, tuple)):
|
|
337
|
+
outs = [outs]
|
|
338
|
+
|
|
339
|
+
acts: Dict[str, np.ndarray] = {}
|
|
340
|
+
# Giris duzlestirilir (build_graph de oyle sayiyor), ortalanmaz:
|
|
341
|
+
# ham piksel/ozellik degerlerini oldugu gibi gormek istiyoruz.
|
|
342
|
+
flat_in = x[0].ravel()
|
|
343
|
+
sel_in = self._picks["__input__"]
|
|
344
|
+
acts["__input__"] = flat_in[sel_in[sel_in < flat_in.shape[0]]].astype("float32")
|
|
345
|
+
for l, o in zip(self.model.layers, outs):
|
|
346
|
+
acts[l.name] = self._reduce(np.asarray(o), self._picks[l.name])
|
|
347
|
+
return acts
|
|
348
|
+
|
|
349
|
+
@staticmethod
|
|
350
|
+
def _reduce(a: np.ndarray, sel: np.ndarray) -> np.ndarray:
|
|
351
|
+
"""(batch, ...) tensorunu secili noronlarin tek boyutlu vektorune indirir.
|
|
352
|
+
|
|
353
|
+
Conv ciktilarinda uzamsal eksenler ortalanir -> kanal basina tek deger,
|
|
354
|
+
yani ekrandaki nokta "bu ozellik haritasi ne kadar aktif" demek olur.
|
|
355
|
+
"""
|
|
356
|
+
a = a[0] if a.ndim > 1 else a # batch'in ilk ornegi
|
|
357
|
+
if a.ndim > 1:
|
|
358
|
+
a = a.mean(axis=tuple(range(a.ndim - 1)))
|
|
359
|
+
sel = sel[sel < a.shape[0]]
|
|
360
|
+
return a[sel].astype("float32")
|
nn3d/monitor.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Egitim sirasinda agi canli yayinlayan Keras callback'i.
|
|
2
|
+
|
|
3
|
+
Bu modul keras'i ICE AKTARIR. `import nn3d` bunu tetiklemez -- paketin
|
|
4
|
+
__init__.py'si `nn3d.Monitor`'a ilk erisildiginde tembel yukler. Boylece
|
|
5
|
+
sema/sunucu tarafi Keras kurulmamis ortamlarda da kullanilabilir kalir.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Dict, Optional, Sequence
|
|
11
|
+
|
|
12
|
+
import keras
|
|
13
|
+
|
|
14
|
+
from . import schema
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Monitor(keras.callbacks.Callback):
|
|
18
|
+
"""Egitimi tarayiciya canli yayinlar.
|
|
19
|
+
|
|
20
|
+
model.fit(X, y, callbacks=[nn3d.Monitor(X[:1], every=20)])
|
|
21
|
+
|
|
22
|
+
`every` neden var: her batch'te ayrica bir ileri yayilim yapmak egitimi
|
|
23
|
+
olcülebilir sekilde yavaslatir. 20 batch'te bir gonderim akici gorunur ve
|
|
24
|
+
maliyeti ihmal edilebilir kalir.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
sample: Any,
|
|
30
|
+
*,
|
|
31
|
+
every: int = 20,
|
|
32
|
+
input_labels: Optional[Sequence[str]] = None,
|
|
33
|
+
output_labels: Optional[Sequence[str]] = None,
|
|
34
|
+
max_neurons: int = schema.DEFAULT_MAX_NEURONS,
|
|
35
|
+
port: int = 8092,
|
|
36
|
+
open_browser: bool = True,
|
|
37
|
+
):
|
|
38
|
+
super().__init__()
|
|
39
|
+
self.sample = sample
|
|
40
|
+
self.every = max(1, int(every))
|
|
41
|
+
self.input_labels = input_labels
|
|
42
|
+
self.output_labels = output_labels
|
|
43
|
+
self.max_neurons = max_neurons
|
|
44
|
+
self.port = port
|
|
45
|
+
self.open_browser = open_browser
|
|
46
|
+
self.view: Optional[Any] = None
|
|
47
|
+
self._epoch = 0
|
|
48
|
+
self._batch = 0
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def url(self) -> Optional[str]:
|
|
52
|
+
return self.view.url if self.view else None
|
|
53
|
+
|
|
54
|
+
def on_train_begin(self, logs: Optional[Dict[str, Any]] = None) -> None:
|
|
55
|
+
from . import show
|
|
56
|
+
|
|
57
|
+
self.view = show(
|
|
58
|
+
self.model,
|
|
59
|
+
sample=self.sample,
|
|
60
|
+
input_labels=self.input_labels,
|
|
61
|
+
output_labels=self.output_labels,
|
|
62
|
+
max_neurons=self.max_neurons,
|
|
63
|
+
port=self.port,
|
|
64
|
+
open_browser=self.open_browser,
|
|
65
|
+
)
|
|
66
|
+
self.view.server.status = "egitim"
|
|
67
|
+
|
|
68
|
+
def on_epoch_begin(self, epoch: int, logs: Optional[Dict[str, Any]] = None) -> None:
|
|
69
|
+
self._epoch = epoch
|
|
70
|
+
|
|
71
|
+
def on_train_batch_end(self, batch: int, logs: Optional[Dict[str, Any]] = None) -> None:
|
|
72
|
+
self._batch += 1
|
|
73
|
+
if self.view is None or self._batch % self.every:
|
|
74
|
+
return
|
|
75
|
+
self._send(self._epoch, logs)
|
|
76
|
+
|
|
77
|
+
def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, Any]] = None) -> None:
|
|
78
|
+
# Epoch sonunda dogrulama metrikleri de geldigi icin her halukarda yolla.
|
|
79
|
+
if self.view is not None:
|
|
80
|
+
self._send(epoch, logs)
|
|
81
|
+
|
|
82
|
+
def on_train_end(self, logs: Optional[Dict[str, Any]] = None) -> None:
|
|
83
|
+
if self.view is not None:
|
|
84
|
+
self.view.server.status = "egitim bitti"
|
|
85
|
+
print(f"[nn3d] egitim bitti - {self.view.url} hala acik")
|
|
86
|
+
|
|
87
|
+
def _send(self, epoch: int, logs: Optional[Dict[str, Any]]) -> None:
|
|
88
|
+
assert self.view is not None
|
|
89
|
+
metrics = {k: float(v) for k, v in (logs or {}).items() if _is_number(v)}
|
|
90
|
+
self.view.update(self.sample, epoch=epoch, metrics=metrics)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_number(v: Any) -> bool:
|
|
94
|
+
try:
|
|
95
|
+
float(v)
|
|
96
|
+
return True
|
|
97
|
+
except (TypeError, ValueError):
|
|
98
|
+
return False
|