blocklearning 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.
- blocklearning/__init__.py +1 -0
- blocklearning/__main__.py +6 -0
- blocklearning/analysis.py +133 -0
- blocklearning/anomaly.py +148 -0
- blocklearning/blocks.py +601 -0
- blocklearning/cli.py +46 -0
- blocklearning/codegen.py +1012 -0
- blocklearning/core.py +861 -0
- blocklearning/data/bearing_uottawa.SOURCE.txt +6 -0
- blocklearning/data/bearing_uottawa.npz +0 -0
- blocklearning/data/concrete.SOURCE.txt +4 -0
- blocklearning/data/concrete.npz +0 -0
- blocklearning/data/digits32.SOURCE.txt +4 -0
- blocklearning/data/digits32.npz +0 -0
- blocklearning/data/ecg_mitdb.SOURCE.txt +6 -0
- blocklearning/data/ecg_mitdb.npz +0 -0
- blocklearning/data/hydraulic.SOURCE.txt +6 -0
- blocklearning/data/hydraulic.npz +0 -0
- blocklearning/data/pcb_det.SOURCE.txt +6 -0
- blocklearning/data/pcb_det.npz +0 -0
- blocklearning/data/pneumatic_seg.SOURCE.txt +8 -0
- blocklearning/data/pneumatic_seg.npz +0 -0
- blocklearning/data/pneumonia28.SOURCE.txt +13 -0
- blocklearning/data/pneumonia28.npz +0 -0
- blocklearning/data/steel_plates.SOURCE.txt +5 -0
- blocklearning/data/steel_plates.npz +0 -0
- blocklearning/data/steel_power.SOURCE.txt +3 -0
- blocklearning/data/steel_power.npz +0 -0
- blocklearning/data/steelblast.SOURCE.txt +4 -0
- blocklearning/data/steelblast.npz +0 -0
- blocklearning/data.py +1158 -0
- blocklearning/detect.py +222 -0
- blocklearning/forecast.py +204 -0
- blocklearning/graph.py +602 -0
- blocklearning/jobs.py +501 -0
- blocklearning/labeling.py +1294 -0
- blocklearning/labeling_sources.py +217 -0
- blocklearning/layers.py +615 -0
- blocklearning/losses.py +199 -0
- blocklearning/multi.py +175 -0
- blocklearning/nn_extra.py +643 -0
- blocklearning/predict.py +344 -0
- blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
- blocklearning/pretrained/mnv3s.SOURCE.txt +6 -0
- blocklearning/pretrained/mnv3s.bin +0 -0
- blocklearning/pretrained/mnv3s.json +1 -0
- blocklearning/pretrained.py +56 -0
- blocklearning/project.py +120 -0
- blocklearning/segment.py +173 -0
- blocklearning/server.py +116 -0
- blocklearning/static/app.js +1986 -0
- blocklearning/static/boot.js +51 -0
- blocklearning/static/demo.jpg +0 -0
- blocklearning/static/demo.webm +0 -0
- blocklearning/static/engine.js +1326 -0
- blocklearning/static/graph.js +1902 -0
- blocklearning/static/index.html +301 -0
- blocklearning/static/label.html +158 -0
- blocklearning/static/label.js +1040 -0
- blocklearning/static/labels.js +227 -0
- blocklearning/static/projects.js +516 -0
- blocklearning/static/store.js +259 -0
- blocklearning/static/style.css +844 -0
- blocklearning/static/train-worker.js +41 -0
- blocklearning/static/web.js +602 -0
- blocklearning/tasks.py +351 -0
- blocklearning/web.py +412 -0
- blocklearning/weblabel.py +316 -0
- blocklearning-0.1.0.dist-info/METADATA +66 -0
- blocklearning-0.1.0.dist-info/RECORD +74 -0
- blocklearning-0.1.0.dist-info/WHEEL +4 -0
- blocklearning-0.1.0.dist-info/entry_points.txt +2 -0
- blocklearning-0.1.0.dist-info/licenses/LICENSE +25 -0
- blocklearning-0.1.0.dist-info/licenses/src/blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""BlockLearning: 딥러닝을 직접 짜기 어려운 사람이 블록을 이어 모델을 만들고 학습해 쓰는 로컬 웹 도구 (`blocklearning`)."""
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""모델 정보(파라미터 수·크기)와 블록 사이 실제 값(activations)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
MAX_POINTS = 200 # 블록 사이 그림의 시점 수 상한
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def model_panel(model) -> dict:
|
|
10
|
+
"""③ 모델 옆 '모델 정보': 파라미터 수와 크기(MB, float32 기준)."""
|
|
11
|
+
params = int(sum(p.numel() for p in model.parameters() if p.requires_grad))
|
|
12
|
+
frozen = int(sum(p.numel() for p in model.parameters() if not p.requires_grad)) # 사전학습 (고정)
|
|
13
|
+
return {"ok": True, "params": params, "frozen": frozen, "mb": (params + frozen) * 4 / 1e6, "message": "", "warnings": []}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _thin(a: np.ndarray) -> list:
|
|
17
|
+
if a.ndim == 2 and a.shape[1] > MAX_POINTS:
|
|
18
|
+
idx = np.round(np.linspace(0, a.shape[1] - 1, MAX_POINTS)).astype(int)
|
|
19
|
+
a = a[:, idx]
|
|
20
|
+
return np.round(a.astype(np.float64), 5).tolist()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def activations(model, x) -> dict:
|
|
24
|
+
"""샘플 하나(모델 입력 모양, 배치 없음)를 넣어 블록마다 출력 값. 키는 model.block_modules의 키."""
|
|
25
|
+
import torch
|
|
26
|
+
if hasattr(model, "trace"): # 그래프 모델: 모든 노드 (Add·Concat 포함)
|
|
27
|
+
model.eval()
|
|
28
|
+
dtype = next(model.parameters()).dtype
|
|
29
|
+
with torch.no_grad():
|
|
30
|
+
vals = model.trace(torch.as_tensor(np.asarray(x)[None], dtype=dtype))
|
|
31
|
+
return {k: _thin(v[0].detach().cpu().numpy()) for k, v in vals.items()}
|
|
32
|
+
seen: dict = {}
|
|
33
|
+
hooks = [m.register_forward_hook(lambda mod, i, o, k=k: seen.__setitem__(k, o))
|
|
34
|
+
for k, m in model.block_modules.items()]
|
|
35
|
+
try:
|
|
36
|
+
model.eval()
|
|
37
|
+
dtype = next(model.parameters()).dtype
|
|
38
|
+
with torch.no_grad():
|
|
39
|
+
model(torch.as_tensor(np.asarray(x)[None], dtype=dtype))
|
|
40
|
+
finally:
|
|
41
|
+
for h in hooks:
|
|
42
|
+
h.remove()
|
|
43
|
+
return {k: _thin(v[0].detach().cpu().numpy()) for k, v in seen.items()}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ATTN_ROWS, ATTN_COLS = 64, 128 # 어텐션 지도 그림의 크기 상한 (질문 위치 × 본 위치)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def attn_view(a: np.ndarray) -> dict:
|
|
50
|
+
"""어텐션 가중치 (질문 T, 본 위치 S) → 화면용: 지도(줄여서)·위치마다 평균으로 받은 주의·첫 자리(CLS)가 본 곳."""
|
|
51
|
+
a = np.asarray(a, dtype=np.float64)
|
|
52
|
+
m = a
|
|
53
|
+
if m.shape[0] > ATTN_ROWS:
|
|
54
|
+
m = m[np.round(np.linspace(0, m.shape[0] - 1, ATTN_ROWS)).astype(int)]
|
|
55
|
+
if m.shape[1] > ATTN_COLS:
|
|
56
|
+
m = m[:, np.round(np.linspace(0, m.shape[1] - 1, ATTN_COLS)).astype(int)]
|
|
57
|
+
r = lambda v: np.round(v, 5).tolist()
|
|
58
|
+
return {"q": int(a.shape[0]), "k": int(a.shape[1]), "map": r(m), "mean": r(a.mean(0)), "first": r(a[0])}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def attention(model, x) -> dict:
|
|
62
|
+
"""샘플 하나를 넣어 어텐션 블록(MultiHeadAttention·CrossAttention·NonLocal·AttentionPool)마다 softmax 가중치
|
|
63
|
+
(head 평균) → {노드 id: attn_view}. 모듈 코드는 그대로 두고, 그 블록이 도는 동안만 torch.softmax의 결과를 받아 둠."""
|
|
64
|
+
import torch
|
|
65
|
+
from blocklearning import nn_extra as NX
|
|
66
|
+
kinds = (NX.MultiHeadAttention, NX.CrossAttention, NX.NonLocal, NX.AttentionPool)
|
|
67
|
+
mods = getattr(model, "block_modules", {}) or {}
|
|
68
|
+
cur, got = [None], {}
|
|
69
|
+
hooks = []
|
|
70
|
+
for k, m in mods.items():
|
|
71
|
+
for sub in m.modules():
|
|
72
|
+
if isinstance(sub, kinds):
|
|
73
|
+
hooks.append(sub.register_forward_pre_hook(lambda mod, i, k=k: cur.__setitem__(0, k)))
|
|
74
|
+
hooks.append(sub.register_forward_hook(lambda mod, i, o: cur.__setitem__(0, None)))
|
|
75
|
+
if not hooks:
|
|
76
|
+
return {}
|
|
77
|
+
real = torch.softmax
|
|
78
|
+
|
|
79
|
+
def soft(t, *a, **kw):
|
|
80
|
+
y = real(t, *a, **kw)
|
|
81
|
+
if cur[0] is not None:
|
|
82
|
+
w = y[0].detach().cpu().numpy()
|
|
83
|
+
got[cur[0]] = w.mean(0) if w.ndim == 3 else (w[None] if w.ndim == 1 else w) # head 평균 · AttentionPool은 (1, S)
|
|
84
|
+
return y
|
|
85
|
+
try:
|
|
86
|
+
torch.softmax = soft
|
|
87
|
+
model.eval()
|
|
88
|
+
dtype = next(model.parameters()).dtype
|
|
89
|
+
with torch.no_grad():
|
|
90
|
+
model(torch.as_tensor(np.asarray(x)[None], dtype=dtype))
|
|
91
|
+
finally:
|
|
92
|
+
torch.softmax = real
|
|
93
|
+
for h in hooks:
|
|
94
|
+
h.remove()
|
|
95
|
+
return {k: attn_view(v) for k, v in got.items()}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _score(out, x, d):
|
|
99
|
+
"""예측을 나타내는 수 하나 (그 기울기가 '어디를 봤나'): 분류는 고른 클래스 점수, 구간 분할은 시점마다 고른 상태 점수의 합,
|
|
100
|
+
정답 여러 개는 머리마다 (고른 클래스 점수·값)의 합, 탐지는 칸마다 '있음' 점수의 합, 오토인코더는 복원 오차, 나머지는 출력의 합.
|
|
101
|
+
웹 엔진(engine.js saliency)과 같은 식."""
|
|
102
|
+
if d.task == "classification":
|
|
103
|
+
return out.max()
|
|
104
|
+
if d.task == "segmentation":
|
|
105
|
+
return out.reshape(d.n_out.n_cls, -1).max(0).values.sum()
|
|
106
|
+
if d.task == "multi":
|
|
107
|
+
return sum(out[h["start"]:h["start"] + h["size"]].max() if h["kind"] == "class" else out[h["start"]] for h in d.n_out.heads)
|
|
108
|
+
if d.task == "detection":
|
|
109
|
+
return out.reshape(d.n_out.per_cell, -1)[0].sum()
|
|
110
|
+
if d.task == "anomaly" and out.numel() == x.numel():
|
|
111
|
+
return ((out - x.reshape(-1)) ** 2).sum()
|
|
112
|
+
return out.sum()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def saliency(model, x, d) -> list:
|
|
116
|
+
"""샘플 하나(모델 입력 모양)에서 입력 값마다 |∂ 예측 / ∂ 입력|, 가장 큰 것이 1. 데이터 순서로 펼치고,
|
|
117
|
+
여러 채널 시계열은 시점마다 채널을 더함 (길이 L)."""
|
|
118
|
+
import torch
|
|
119
|
+
model.eval()
|
|
120
|
+
dtype = next(model.parameters()).dtype
|
|
121
|
+
xt = torch.as_tensor(np.asarray(x)[None], dtype=dtype).requires_grad_(True)
|
|
122
|
+
out = model(xt)[0].reshape(-1)
|
|
123
|
+
xd = xt[0].transpose(0, 1) if getattr(model, "kind", "") == "rnn" else xt[0] # 순환 모델 입력 (L, C) → 데이터 순서 (C, L)
|
|
124
|
+
_score(out, xd, d).backward()
|
|
125
|
+
g = xt.grad[0]
|
|
126
|
+
if getattr(model, "kind", "") == "rnn":
|
|
127
|
+
g = g.transpose(0, 1)
|
|
128
|
+
g = g.abs().double().cpu().numpy()
|
|
129
|
+
if not d.image and g.ndim == 2 and g.shape[0] > 1: # 여러 채널: 시점마다 더함
|
|
130
|
+
g = g.sum(0)
|
|
131
|
+
g = g.reshape(-1)
|
|
132
|
+
hi = float(g.max()) or 1.0
|
|
133
|
+
return np.round(g / hi, 4).tolist()
|
blocklearning/anomaly.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""이상 탐지 (오토인코더): 정상 샘플만으로 '입력을 그대로 되살리기(복원)'를 배우고, 잘 못 되살리는 샘플을 이상으로 본다.
|
|
2
|
+
|
|
3
|
+
데이터는 분류처럼 정답(정상·이상 종류)이 붙은 것에서 만든다. 정상 클래스 하나를 정하고 나머지는 모두 '이상'.
|
|
4
|
+
학습에는 학습 몫의 정상만 쓰고, 학습 몫에 있던 이상 샘플은 시험으로 옮긴다 (평가에 쓸 이상이 늘어남).
|
|
5
|
+
정상만 있는 데이터도 된다 (그때는 AUC 대신 정상의 복원 오차만 보여 줌).
|
|
6
|
+
이상 점수 = 정규화한 값에서 (입력 − 복원)²의 평균. 기준값(이 값보다 크면 이상)은 학습 정상 점수의 95% 지점.
|
|
7
|
+
|
|
8
|
+
출력 블록을 '정상과의 거리'로 하면 (nn_extra.NormalDistance) 되살리지 않고, 정상 샘플의 특징 분포(평균·주성분)에서
|
|
9
|
+
떨어진 정도를 점수로 바로 냄 (모델 출력이 점수 하나). 사전학습 블록 바로 뒤에 둠: 그림 이상 탐지에서 훨씬 잘 됨.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
NORMAL_NAMES = ("정상", "normal", "ok", "good", "양품", "0", "false", "n")
|
|
16
|
+
QUANTILE = 0.95 # 기준값: 학습 정상의 95%가 이 아래
|
|
17
|
+
N_SHOW = 6 # 결과 화면에 그릴 샘플 (점수 높은 것부터)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def pick_normal(classes: list, y: np.ndarray, normal=None) -> int:
|
|
21
|
+
"""정상 클래스 번호: 고른 이름 → 이름이 정상·normal·양품 같은 것 → 가장 많은 것."""
|
|
22
|
+
names = [str(c) for c in classes]
|
|
23
|
+
if normal is not None and str(normal) in names:
|
|
24
|
+
return names.index(str(normal))
|
|
25
|
+
for k, c in enumerate(names):
|
|
26
|
+
if c.strip().lower() in NORMAL_NAMES:
|
|
27
|
+
return k
|
|
28
|
+
return int(np.bincount(np.asarray(y, dtype=int), minlength=len(names)).argmax())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_anomaly(d, normal=None):
|
|
32
|
+
"""분류 Dataset → 이상 탐지 Dataset (task "anomaly", classes [정상 이름, "이상"], y 0 정상 · 1 이상)."""
|
|
33
|
+
from blocklearning.data import DataError, Dataset, Issue
|
|
34
|
+
y_all = np.concatenate([d.y_train, d.y_test]) if len(d.classes) else np.zeros(len(d.X_train) + len(d.X_test), int)
|
|
35
|
+
names = [str(c) for c in d.classes] or ["정상"]
|
|
36
|
+
k = pick_normal(names, y_all, normal)
|
|
37
|
+
raw_tr, raw_te = d.raw(d.X_train), d.raw(d.X_test)
|
|
38
|
+
ab_tr = np.asarray(d.y_train) != k if len(d.classes) else np.zeros(len(raw_tr), bool)
|
|
39
|
+
ab_te = np.asarray(d.y_test) != k if len(d.classes) else np.zeros(len(raw_te), bool)
|
|
40
|
+
Xtr = raw_tr[~ab_tr]
|
|
41
|
+
Xte = np.concatenate([raw_te, raw_tr[ab_tr]])
|
|
42
|
+
yte = np.concatenate([ab_te, np.ones(int(ab_tr.sum()), bool)]).astype(np.int64)
|
|
43
|
+
if len(Xtr) < 10:
|
|
44
|
+
raise DataError([Issue(None, None, f"학습에 쓸 정상 샘플이 {len(Xtr)}개뿐임 (정상 = '{names[k]}')",
|
|
45
|
+
"정상 샘플을 10개 이상 모으거나, 정상 클래스를 다시 고르세요")])
|
|
46
|
+
norm = (d.source or {}).get("normalize", True)
|
|
47
|
+
if norm and d.image:
|
|
48
|
+
m, s = float(Xtr.mean()), float(Xtr.std()) or 1.0
|
|
49
|
+
mean, std = np.full(Xtr.shape[1], m), np.full(Xtr.shape[1], s)
|
|
50
|
+
elif norm:
|
|
51
|
+
mean, std = Xtr.mean(0), Xtr.std(0)
|
|
52
|
+
std = np.where(std > 0, std, 1.0)
|
|
53
|
+
else:
|
|
54
|
+
mean, std = np.zeros(Xtr.shape[1]), np.ones(Xtr.shape[1])
|
|
55
|
+
src = dict(d.source or {}, task="anomaly", normal=names[k])
|
|
56
|
+
others = [c for i, c in enumerate(names) if i != k]
|
|
57
|
+
extra = {"normal": names[k], "others": others, "n_anomaly": int(yte.sum())}
|
|
58
|
+
return Dataset((Xtr - mean) / std, (Xte - mean) / std, np.zeros(len(Xtr), np.int64), yte, "anomaly",
|
|
59
|
+
[names[k], "이상"], d.length, mean, std, src, list(d.features), d.image, None, extra)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def distance_mode(out: np.ndarray, X: np.ndarray) -> bool:
|
|
63
|
+
"""모델이 점수 하나를 바로 냄 (출력 '정상과의 거리')."""
|
|
64
|
+
return np.asarray(out).reshape(len(X), -1).shape[1] == 1 and np.asarray(X).reshape(len(X), -1).shape[1] > 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def scores(out: np.ndarray, X: np.ndarray) -> np.ndarray:
|
|
68
|
+
"""샘플마다 이상 점수 = 정규화한 값에서 (입력 − 복원)²의 평균. 출력이 '정상과의 거리'면 그 값."""
|
|
69
|
+
o = np.asarray(out, dtype=float).reshape(len(X), -1)
|
|
70
|
+
if distance_mode(o, X):
|
|
71
|
+
return o[:, 0]
|
|
72
|
+
return ((o - np.asarray(X, dtype=float).reshape(len(X), -1)) ** 2).mean(1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def fit_distance(F: np.ndarray, k: int) -> dict:
|
|
76
|
+
"""정상 샘플의 특징 F (n, C) → '정상과의 거리' 값: 평균, 분산이 큰 방향(주성분) k개, 그 분산의 역수, 나머지 방향 평균 분산의 역수.
|
|
77
|
+
점수 = (주성분 방향마다 거리²/분산의 합 + 나머지 거리²/나머지 분산) / C — Mahalanobis 거리를 주성분 k개로 줄인 것."""
|
|
78
|
+
F = np.asarray(F, dtype=np.float64)
|
|
79
|
+
n, C = F.shape
|
|
80
|
+
mu = F.mean(0)
|
|
81
|
+
D = F - mu
|
|
82
|
+
lam, U = np.linalg.eigh(D.T @ D / max(n, 1))
|
|
83
|
+
lam, U = np.clip(lam[::-1], 0, None), U[:, ::-1]
|
|
84
|
+
eps = 1e-3 * max(float(lam[0]), 1e-12)
|
|
85
|
+
m = min(k, C, max(n - 1, 1))
|
|
86
|
+
basis, inv_var = np.zeros((k, C)), np.zeros(k)
|
|
87
|
+
basis[:m], inv_var[:m] = U[:, :m].T, 1.0 / (lam[:m] + eps)
|
|
88
|
+
rest = float(lam[m:].mean()) if C > m else 0.0
|
|
89
|
+
return {"mean": mu.astype(np.float32), "basis": basis.astype(np.float32), "inv_var": inv_var.astype(np.float32),
|
|
90
|
+
"inv_rest": np.array([1.0 / (rest + eps)], np.float32)}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def auc(s: np.ndarray, y: np.ndarray) -> float:
|
|
94
|
+
"""ROC AUC: 이상 하나와 정상 하나를 뽑았을 때 이상의 점수가 더 클 확률 (같으면 반). 둘 중 하나가 없으면 NaN."""
|
|
95
|
+
s, y = np.asarray(s, dtype=float), np.asarray(y, dtype=int)
|
|
96
|
+
pos, neg = s[y == 1], s[y == 0]
|
|
97
|
+
if not len(pos) or not len(neg):
|
|
98
|
+
return float("nan")
|
|
99
|
+
order = np.argsort(np.concatenate([neg, pos]), kind="mergesort")
|
|
100
|
+
allv = np.concatenate([neg, pos])[order]
|
|
101
|
+
ranks = np.empty(len(allv))
|
|
102
|
+
i = 0
|
|
103
|
+
while i < len(allv): # 같은 값은 평균 순위
|
|
104
|
+
j = i
|
|
105
|
+
while j + 1 < len(allv) and allv[j + 1] == allv[i]:
|
|
106
|
+
j += 1
|
|
107
|
+
ranks[i:j + 1] = (i + j) / 2 + 1
|
|
108
|
+
i = j + 1
|
|
109
|
+
r = np.empty(len(allv))
|
|
110
|
+
r[order] = ranks
|
|
111
|
+
return float((r[len(neg):].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def metric(out: np.ndarray, X: np.ndarray, y: np.ndarray) -> float:
|
|
115
|
+
"""학습 곡선의 성적: 이상이 있으면 AUC, 정상만 있으면 평균 이상 점수 (낮을수록 잘 되살림)."""
|
|
116
|
+
s = scores(out, X)
|
|
117
|
+
return auc(s, y) if (np.asarray(y) == 1).any() and (np.asarray(y) == 0).any() else float(s.mean())
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def metric_name(d) -> str:
|
|
121
|
+
return "auc" if (np.asarray(d.y_test) == 1).any() and (np.asarray(d.y_test) == 0).any() else "recon"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def at_threshold(s: np.ndarray, y: np.ndarray, th: float) -> dict:
|
|
125
|
+
"""기준값으로 나눈 결과: 이상을 이상으로(tp)·정상을 이상으로(fp)·이상을 놓침(fn)·정상을 정상으로(tn)."""
|
|
126
|
+
p, y = np.asarray(s) > th, np.asarray(y) == 1
|
|
127
|
+
tp, fp, fn, tn = int((p & y).sum()), int((p & ~y).sum()), int((~p & y).sum()), int((~p & ~y).sum())
|
|
128
|
+
return {"tp": tp, "fp": fp, "fn": fn, "tn": tn, "precision": tp / (tp + fp) if tp + fp else None,
|
|
129
|
+
"recall": tp / (tp + fn) if tp + fn else None}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def result(out: np.ndarray, out_train: np.ndarray, d) -> dict:
|
|
133
|
+
"""결과 화면: 점수(시험 전체·학습 정상), 기준값, AUC, 기준값에서 나눈 결과, 점수 높은 샘플의 입력·복원."""
|
|
134
|
+
s = scores(out, d.X_test)
|
|
135
|
+
s_tr = scores(out_train, d.X_train)
|
|
136
|
+
th = float(np.quantile(s_tr, QUANTILE))
|
|
137
|
+
o = np.asarray(out, dtype=float).reshape(len(d.X_test), -1)
|
|
138
|
+
dist = distance_mode(o, d.X_test)
|
|
139
|
+
show = [int(i) for i in np.argsort(-s)[:N_SHOW]]
|
|
140
|
+
normal_low = [int(i) for i in np.argsort(s)[:2] if int(i) not in show] # 비교용: 가장 잘 되살린 정상
|
|
141
|
+
r5 = lambda a: [round(float(x), 5) for x in a]
|
|
142
|
+
raw = d.raw(d.X_test)
|
|
143
|
+
rec = None if dist else o * d.std + d.mean
|
|
144
|
+
return {"scores": r5(s), "train_scores": r5(s_tr), "threshold": th, "labels": [int(v) for v in d.y_test],
|
|
145
|
+
"auc": auc(s, d.y_test), "at": at_threshold(s, d.y_test, th), "mode": "distance" if dist else "recon",
|
|
146
|
+
"ae_samples": [{"index": i, "score": round(float(s[i]), 5), "label": int(d.y_test[i]), "x": r5(raw[i]),
|
|
147
|
+
"recon": None if dist else r5(rec[i]), "err": None if dist else r5((o[i] - d.X_test[i]) ** 2)}
|
|
148
|
+
for i in show + normal_low]}
|