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
blocklearning/detect.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""객체 탐지 (YOLO 첫 버전과 같은 격자 방식): 그림을 격자로 나누고, 칸마다 '여기에 사물의 가운데가 있나, 상자는 어디·얼마나,
|
|
2
|
+
무슨 클래스인가'를 한 번에 맞힌다.
|
|
3
|
+
|
|
4
|
+
- 모델 출력 한 줄 = (칸마다 값 수 A, 격자 G, 격자 G)를 펼친 것. A = 5 + 클래스 수:
|
|
5
|
+
0 있음(logit) · 1·2 칸 안의 가운데 위치(sigmoid) · 3·4 너비·높이의 제곱근(sigmoid, 그림 크기 비율) · 5… 클래스(softmax)
|
|
6
|
+
- 정답 상자: [클래스 번호, x, y, w, h] (왼쪽 위 기준, 그림 크기에 대한 0–1 비율)
|
|
7
|
+
- 지표: mAP@0.5 (클래스마다 AP를 구해 평균, 예측과 정답 상자가 50% 이상 겹치면 맞음)
|
|
8
|
+
|
|
9
|
+
numpy만 쓴다 (브라우저 Pyodide에서도 돈다). torch 손실은 torch_loss, 같은 식을 웹 엔진(engine.js)도 쓴다.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
DET_SIZES = (32, 48, 64, 96) # 탐지에 쓰는 그림 크기 (정사각형)
|
|
16
|
+
DEFAULT_SIZE = 64
|
|
17
|
+
STRIDE = 8 # 8픽셀 = 격자 한 칸 (2×2 Pool을 세 번)
|
|
18
|
+
LAMBDA_COORD = 5.0 # 손실: 상자 위치·크기 무게
|
|
19
|
+
LAMBDA_NOOBJ = 0.5 # 손실: 사물이 없는 칸의 '없음' 무게 (없는 칸이 훨씬 많음)
|
|
20
|
+
SCORE_MIN = 0.05 # mAP를 구할 때 쓰는 가장 낮은 점수
|
|
21
|
+
SHOW_SCORE = 0.5 # 화면에 보이는 상자의 기본 점수
|
|
22
|
+
NMS_IOU = 0.5 # 같은 클래스 상자가 이만큼 겹치면 점수가 낮은 쪽을 버림
|
|
23
|
+
MATCH_IOU = 0.5 # 정답과 이만큼 겹치면 맞음
|
|
24
|
+
MAX_DET = 50 # 그림 하나에서 찾는 상자 수 상한
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DetOut(int):
|
|
28
|
+
"""탐지 과제의 모델 출력 크기 (격자² × 칸마다 값 수). int처럼 쓰이고, 격자·클래스 수를 함께 지님 →
|
|
29
|
+
모델 검사·만들기·코드가 Output 블록을 '격자 칸마다 1×1 필터'로 만든다."""
|
|
30
|
+
|
|
31
|
+
def __new__(cls, grid: int, n_cls: int):
|
|
32
|
+
o = super().__new__(cls, grid * grid * (5 + n_cls))
|
|
33
|
+
o.grid, o.n_cls, o.per_cell = int(grid), int(n_cls), 5 + int(n_cls)
|
|
34
|
+
return o
|
|
35
|
+
|
|
36
|
+
def __getnewargs__(self):
|
|
37
|
+
return (self.grid, self.n_cls)
|
|
38
|
+
|
|
39
|
+
def __reduce__(self):
|
|
40
|
+
return (DetOut, (self.grid, self.n_cls))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def grid_of(size: int) -> int:
|
|
44
|
+
return max(1, int(size) // STRIDE)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _sig(x):
|
|
48
|
+
return 1.0 / (1.0 + np.exp(-np.clip(x, -60, 60)))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def encode(boxes: list, grid: int, n_cls: int) -> np.ndarray:
|
|
52
|
+
"""정답 상자들 → 목표값 한 줄 (모델 출력과 같은 자리). 가운데가 같은 칸에 둘이면 큰 상자만 (YOLO 첫 버전과 같음)."""
|
|
53
|
+
A, G = 5 + n_cls, grid
|
|
54
|
+
t = np.zeros((A, G, G))
|
|
55
|
+
for k, x, y, w, h in sorted(boxes, key=lambda b: -b[3] * b[4]):
|
|
56
|
+
cx, cy = x + w / 2, y + h / 2
|
|
57
|
+
gx, gy = min(G - 1, max(0, int(cx * G))), min(G - 1, max(0, int(cy * G)))
|
|
58
|
+
if t[0, gy, gx]:
|
|
59
|
+
continue
|
|
60
|
+
t[0, gy, gx] = 1
|
|
61
|
+
t[1, gy, gx], t[2, gy, gx] = cx * G - gx, cy * G - gy
|
|
62
|
+
t[3, gy, gx], t[4, gy, gx] = np.sqrt(max(w, 0.0)), np.sqrt(max(h, 0.0))
|
|
63
|
+
t[5 + int(k), gy, gx] = 1
|
|
64
|
+
return t.reshape(-1)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def iou(a, b) -> float:
|
|
68
|
+
"""[x, y, w, h] 두 상자의 겹친 넓이 / 합친 넓이."""
|
|
69
|
+
x0, y0 = max(a[0], b[0]), max(a[1], b[1])
|
|
70
|
+
x1, y1 = min(a[0] + a[2], b[0] + b[2]), min(a[1] + a[3], b[1] + b[3])
|
|
71
|
+
inter = max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
|
72
|
+
union = a[2] * a[3] + b[2] * b[3] - inter
|
|
73
|
+
return inter / union if union > 0 else 0.0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def decode(row, grid: int, n_cls: int, score_min: float = SCORE_MIN) -> list:
|
|
77
|
+
"""모델 출력 한 줄 → 찾은 상자 [[클래스 번호, 점수, x, y, w, h], …] (점수 높은 순, 같은 클래스끼리 겹친 것은 뺌).
|
|
78
|
+
점수 = '있음' 확률 × 그 클래스 확률."""
|
|
79
|
+
A, G = 5 + n_cls, grid
|
|
80
|
+
o = np.asarray(row, dtype=np.float64).reshape(A, G, G)
|
|
81
|
+
obj = _sig(o[0])
|
|
82
|
+
if n_cls > 1:
|
|
83
|
+
e = np.exp(o[5:] - o[5:].max(0, keepdims=True))
|
|
84
|
+
prob = e / e.sum(0, keepdims=True)
|
|
85
|
+
else:
|
|
86
|
+
prob = np.ones((1, G, G))
|
|
87
|
+
k = prob.argmax(0)
|
|
88
|
+
score = obj * prob.max(0)
|
|
89
|
+
cand = []
|
|
90
|
+
for gy, gx in zip(*np.nonzero(score >= score_min)):
|
|
91
|
+
cx, cy = (gx + _sig(o[1, gy, gx])) / G, (gy + _sig(o[2, gy, gx])) / G
|
|
92
|
+
w, h = _sig(o[3, gy, gx]) ** 2, _sig(o[4, gy, gx]) ** 2
|
|
93
|
+
x0, y0, x1, y1 = max(0.0, cx - w / 2), max(0.0, cy - h / 2), min(1.0, cx + w / 2), min(1.0, cy + h / 2)
|
|
94
|
+
if x1 > x0 and y1 > y0:
|
|
95
|
+
cand.append([int(k[gy, gx]), float(score[gy, gx]), x0, y0, x1 - x0, y1 - y0])
|
|
96
|
+
return nms(cand)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def nms(cand: list, thr: float = NMS_IOU, max_det: int = MAX_DET) -> list:
|
|
100
|
+
"""점수 높은 순으로 고르고, 이미 고른 같은 클래스 상자와 thr 넘게 겹치면 버림."""
|
|
101
|
+
keep = []
|
|
102
|
+
for c in sorted(cand, key=lambda b: (-b[1], b[0], b[2], b[3])):
|
|
103
|
+
if all(c[0] != q[0] or iou(c[2:], q[2:]) <= thr for q in keep):
|
|
104
|
+
keep.append(c)
|
|
105
|
+
if len(keep) >= max_det:
|
|
106
|
+
break
|
|
107
|
+
return keep
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _match(preds: list, gts: list, k: int, thr: float):
|
|
111
|
+
"""그림 하나·클래스 k: 점수 높은 예측부터 아직 안 맞힌 정답 중 가장 많이 겹친 것과 짝 → [(점수, 맞음)]."""
|
|
112
|
+
used = [False] * len(gts)
|
|
113
|
+
out = []
|
|
114
|
+
for p in sorted((p for p in preds if p[0] == k), key=lambda p: -p[1]):
|
|
115
|
+
best, j = 0.0, -1
|
|
116
|
+
for i, g in enumerate(gts):
|
|
117
|
+
if g[0] == k and not used[i]:
|
|
118
|
+
v = iou(p[2:], g[1:])
|
|
119
|
+
if v > best:
|
|
120
|
+
best, j = v, i
|
|
121
|
+
ok = bool(j >= 0 and best >= thr)
|
|
122
|
+
if ok:
|
|
123
|
+
used[j] = True
|
|
124
|
+
out.append((p[1], ok))
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def average_precision(preds: list, gts: list, n_cls: int, thr: float = MATCH_IOU) -> tuple:
|
|
129
|
+
"""그림마다 예측·정답 → (mAP, 클래스마다 AP (정답이 없는 클래스는 None)). AP는 정밀도-재현율 곡선 아래 넓이
|
|
130
|
+
(재현율이 오를 때마다 그 뒤 가장 높은 정밀도를 씀, VOC 2010 이후·COCO와 같은 방식)."""
|
|
131
|
+
aps = []
|
|
132
|
+
for k in range(n_cls):
|
|
133
|
+
n_pos = sum(1 for g in gts for b in g if b[0] == k)
|
|
134
|
+
if not n_pos:
|
|
135
|
+
aps.append(None)
|
|
136
|
+
continue
|
|
137
|
+
hits = sorted((h for p, g in zip(preds, gts) for h in _match(p, g, k, thr)), key=lambda h: -h[0])
|
|
138
|
+
tp = np.cumsum([1 if ok else 0 for _, ok in hits]) if hits else np.zeros(0)
|
|
139
|
+
fp = np.cumsum([0 if ok else 1 for _, ok in hits]) if hits else np.zeros(0)
|
|
140
|
+
rec = np.concatenate([[0.0], tp / n_pos, [1.0]])
|
|
141
|
+
prec = np.concatenate([[1.0], tp / np.maximum(tp + fp, 1), [0.0]]) if hits else np.array([1.0, 0.0, 0.0])
|
|
142
|
+
if not hits:
|
|
143
|
+
rec = np.array([0.0, 0.0, 1.0])
|
|
144
|
+
for i in range(len(prec) - 2, -1, -1):
|
|
145
|
+
prec[i] = max(prec[i], prec[i + 1])
|
|
146
|
+
ap = float(np.sum((rec[1:] - rec[:-1]) * prec[1:]))
|
|
147
|
+
aps.append(round(ap, 6))
|
|
148
|
+
have = [a for a in aps if a is not None]
|
|
149
|
+
return (float(np.mean(have)) if have else 0.0), aps
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def precision_recall(preds: list, gts: list, n_cls: int, score: float = SHOW_SCORE, thr: float = MATCH_IOU) -> dict:
|
|
153
|
+
"""점수 score 이상만 볼 때: 맞게 찾음(tp)·잘못 찾음(fp)·놓침(fn), 정밀도·재현율."""
|
|
154
|
+
tp = fp = 0
|
|
155
|
+
for p, g in zip(preds, gts):
|
|
156
|
+
shown = [q for q in p if q[1] >= score]
|
|
157
|
+
for k in range(n_cls):
|
|
158
|
+
for _, ok in _match(shown, g, k, thr):
|
|
159
|
+
tp, fp = tp + ok, fp + (not ok)
|
|
160
|
+
n_gt = sum(len(g) for g in gts)
|
|
161
|
+
fn = n_gt - tp
|
|
162
|
+
return {"tp": int(tp), "fp": int(fp), "fn": int(fn), "precision": tp / (tp + fp) if tp + fp else None,
|
|
163
|
+
"recall": tp / n_gt if n_gt else None}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def decode_all(out, grid: int, n_cls: int, score_min: float = SCORE_MIN) -> list:
|
|
167
|
+
out = np.asarray(out, dtype=np.float64).reshape(len(out), -1)
|
|
168
|
+
return [decode(r, grid, n_cls, score_min) for r in out]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def metric(out, gts: list, grid: int, n_cls: int) -> float:
|
|
172
|
+
"""시험 지표 mAP@0.5 (모델 출력 전체, 그림마다 정답)."""
|
|
173
|
+
return average_precision(decode_all(out, grid, n_cls), gts, n_cls)[0]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def rounded(preds: list, score_min: float = 0.25) -> list:
|
|
177
|
+
"""화면·저장용: 점수 score_min 이상만, 소수 넷째 자리."""
|
|
178
|
+
return [[[int(p[0])] + [round(float(v), 4) for v in p[1:]] for p in ps if p[1] >= score_min] for ps in preds]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def result(out, gts: list, grid: int, n_cls: int) -> dict:
|
|
182
|
+
"""학습이 끝난 뒤 결과: mAP, 클래스마다 AP, 점수 0.5에서 정밀도·재현율, 시험 그림마다 찾은 상자."""
|
|
183
|
+
preds = decode_all(out, grid, n_cls)
|
|
184
|
+
m, aps = average_precision(preds, gts, n_cls)
|
|
185
|
+
return {"test_metric": m, "ap": aps, "pr": precision_recall(preds, gts, n_cls), "det_pred": rounded(preds)}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def torch_loss(out, target, grid: int, per_cell: int):
|
|
189
|
+
"""YOLO 첫 버전식 손실 (묶음 평균): 있음(BCE) + 사물 칸의 위치·크기 제곱 오차 × 5 + 클래스 교차 엔트로피.
|
|
190
|
+
없는 칸의 '없음'은 무게 0.5. 웹 엔진(engine.js detLoss)과 같은 식."""
|
|
191
|
+
import torch
|
|
192
|
+
import torch.nn.functional as F
|
|
193
|
+
N = out.shape[0]
|
|
194
|
+
o = out.reshape(N, per_cell, grid, grid)
|
|
195
|
+
t = target.reshape(N, per_cell, grid, grid)
|
|
196
|
+
pos = t[:, 0]
|
|
197
|
+
bce = F.binary_cross_entropy_with_logits(o[:, 0], pos, reduction="none")
|
|
198
|
+
loss = (bce * (pos + LAMBDA_NOOBJ * (1 - pos))).sum()
|
|
199
|
+
loss = loss + LAMBDA_COORD * (((torch.sigmoid(o[:, 1:5]) - t[:, 1:5]) ** 2).sum(1) * pos).sum()
|
|
200
|
+
if per_cell > 6:
|
|
201
|
+
loss = loss + (-(t[:, 5:] * F.log_softmax(o[:, 5:], 1)).sum(1) * pos).sum()
|
|
202
|
+
return loss / N
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# ---------------------------------------------------------------- 라벨링 도형 → 상자
|
|
206
|
+
|
|
207
|
+
def shape_box(s: list, W: float, H: float):
|
|
208
|
+
"""라벨링 도형 → [x, y, w, h] (0–1) 또는 None (점). 다각형·원은 감싸는 상자."""
|
|
209
|
+
kind = s[0] if isinstance(s[0], str) else "box"
|
|
210
|
+
if kind == "pt":
|
|
211
|
+
return None
|
|
212
|
+
if kind == "poly":
|
|
213
|
+
xs, ys = [p[0] for p in s[1]], [p[1] for p in s[1]]
|
|
214
|
+
x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys)
|
|
215
|
+
elif kind == "circle":
|
|
216
|
+
cx, cy, r = s[1], s[2], s[3]
|
|
217
|
+
ry = r * W / max(H, 1e-9)
|
|
218
|
+
x0, y0, x1, y1 = cx - r, cy - ry, cx + r, cy + ry
|
|
219
|
+
else:
|
|
220
|
+
x0, y0, x1, y1 = s[0], s[1], s[0] + s[2], s[1] + s[3]
|
|
221
|
+
x0, y0, x1, y1 = max(0.0, x0), max(0.0, y0), min(1.0, x1), min(1.0, y1)
|
|
222
|
+
return [x0, y0, x1 - x0, y1 - y0] if x1 - x0 > 1e-4 and y1 - y0 > 1e-4 else None
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""시계열 예측 (미래 값): 긴 신호 하나를 '지난 L개 → 다음 H개' 창으로 잘라 학습한다.
|
|
2
|
+
|
|
3
|
+
시험 창은 신호의 뒤쪽 구간에서만 만든다 (시간 순서 그대로 나눔 → 미래 값이 학습에 새지 않음). 시험 창의 입력은
|
|
4
|
+
나눈 지점 앞의 값을 써도 되지만, 맞힐 값(다음 H개)은 모두 나눈 지점 뒤에 있다.
|
|
5
|
+
정규화는 학습 구간의 평균·표준편차 하나 (시점마다가 아니라 신호 전체에 하나: 입력과 맞힐 값이 같은 단위).
|
|
6
|
+
정답(다음 H개)은 원래 단위 그대로 두고, 학습할 때 정규화했다가 출력층에 되돌림을 접어 넣는다 (회귀와 같음).
|
|
7
|
+
시각을 알면 (예시 데이터·CSV의 시각 열) 하루 중 시각·요일을 sin·cos 채널로 함께 넣는다: 값 채널이 먼저,
|
|
8
|
+
X는 채널마다 L개를 이어 붙인 것 (다른 시계열 채널과 같은 모양). 공장 전력처럼 주말·밤에 크게 바뀌는 신호에서
|
|
9
|
+
지난 값만으로는 '다음이 무슨 요일인지'를 모르기 때문.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
MIN_TRAIN = 10 # 학습 창 최소 개수
|
|
18
|
+
MAX_TRAIN = 4000 # 학습 창이 이보다 많으면 간격(stride)을 늘림 (브라우저 학습 시간)
|
|
19
|
+
N_SAMPLES = 6 # 결과 화면의 예시 창 수
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def windows(v: np.ndarray, L: int, H: int, stride: int) -> tuple:
|
|
23
|
+
"""신호 → (X (창 수, L), Y (창 수, H)). 창 시작은 0, stride, 2·stride, …"""
|
|
24
|
+
starts = np.arange(0, len(v) - L - H + 1, max(1, stride))
|
|
25
|
+
if not len(starts):
|
|
26
|
+
return np.zeros((0, L)), np.zeros((0, H))
|
|
27
|
+
X = np.stack([v[s:s + L] for s in starts])
|
|
28
|
+
Y = np.stack([v[s + L:s + L + H] for s in starts])
|
|
29
|
+
return X, Y
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
DAY = 86400
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def calendar(times) -> tuple:
|
|
36
|
+
"""시각 (datetime64 배열) → (채널 (k, 점 수), 이름 k개). 하루 중 시각은 간격이 하루보다 짧을 때만, 요일은 일주일보다
|
|
37
|
+
짧을 때만 (그보다 길면 늘 같은 값). 둘 다 아니면 (None, [])."""
|
|
38
|
+
t = np.asarray(times, dtype="datetime64[s]")
|
|
39
|
+
if len(t) < 2:
|
|
40
|
+
return None, []
|
|
41
|
+
step = float(np.median(np.diff(t).astype(np.int64)))
|
|
42
|
+
days = t.astype("datetime64[D]")
|
|
43
|
+
sec = (t - days).astype(np.int64).astype(float)
|
|
44
|
+
dow = (days.astype(np.int64) + 3) % 7 # 1970-01-01은 목요일 → 월요일 0
|
|
45
|
+
rows, names = [], []
|
|
46
|
+
if 0 < step < DAY:
|
|
47
|
+
a = 2 * np.pi * sec / DAY
|
|
48
|
+
rows += [np.sin(a), np.cos(a)]
|
|
49
|
+
names += ["시각 sin", "시각 cos"]
|
|
50
|
+
if 0 < step < 7 * DAY:
|
|
51
|
+
a = 2 * np.pi * (dow + sec / DAY) / 7
|
|
52
|
+
rows += [np.sin(a), np.cos(a)]
|
|
53
|
+
names += ["요일 sin", "요일 cos"]
|
|
54
|
+
return (np.stack(rows), names) if rows else (None, [])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
TIME_FORMATS = ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M", "%Y-%m-%d",
|
|
58
|
+
"%Y/%m/%d %H:%M:%S", "%Y/%m/%d %H:%M", "%Y/%m/%d", "%Y.%m.%d %H:%M:%S", "%Y.%m.%d %H:%M", "%Y.%m.%d",
|
|
59
|
+
"%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M", "%m/%d/%Y",
|
|
60
|
+
"%d-%m-%Y %H:%M:%S", "%d-%m-%Y %H:%M", "%d-%m-%Y", "%Y%m%d%H%M", "%Y%m%d")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_times(cells: list):
|
|
64
|
+
"""글자 칸들 → datetime64[s] 배열 (모두 같은 형식으로 읽히고 시간 순서대로 늘어날 때만), 아니면 None.
|
|
65
|
+
일·월 순서가 모호하면 (01/02/2018) 시간 순서대로 늘어나는 쪽."""
|
|
66
|
+
cells = [c.strip() for c in cells]
|
|
67
|
+
if len(cells) < 2 or not all(cells):
|
|
68
|
+
return None
|
|
69
|
+
for fmt in TIME_FORMATS:
|
|
70
|
+
try:
|
|
71
|
+
datetime.strptime(cells[0], fmt)
|
|
72
|
+
t = np.array([datetime.strptime(c, fmt) for c in cells], dtype="datetime64[s]")
|
|
73
|
+
except ValueError:
|
|
74
|
+
continue
|
|
75
|
+
if np.all(np.diff(t).astype(np.int64) > 0):
|
|
76
|
+
return t
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_times(names: list, rows: list, nums: list):
|
|
81
|
+
"""CSV에서 시각 열 찾기: 숫자 열이 아니고 모든 행이 날짜·시각으로 읽히는 첫 열 → (열 이름, datetime64 배열) 또는 (None, None)."""
|
|
82
|
+
for j, n in enumerate(names):
|
|
83
|
+
if n in nums:
|
|
84
|
+
continue
|
|
85
|
+
t = parse_times([r[j] if j < len(r) else "" for _, r in rows])
|
|
86
|
+
if t is not None:
|
|
87
|
+
return n, t
|
|
88
|
+
return None, None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def window_channels(v: np.ndarray, cal, L: int, H: int, stride: int) -> tuple:
|
|
92
|
+
"""값 신호와 (있으면) 시각 채널 → (X (창 수, (1 + k)·L), Y (창 수, H)). X는 값 L개 다음 채널마다 L개."""
|
|
93
|
+
X, Y = windows(v, L, H, stride)
|
|
94
|
+
if cal is not None:
|
|
95
|
+
X = np.concatenate([X] + [windows(c, L, H, stride)[0] for c in cal], axis=1)
|
|
96
|
+
return X, Y
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def history(d, X: np.ndarray) -> np.ndarray:
|
|
100
|
+
"""창의 지난 값 (원래 단위): 시각 채널이 있어도 값 채널만."""
|
|
101
|
+
return d.raw(np.asarray(X, dtype=np.float64))[..., :int(d.length)]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def defaults(n: int) -> tuple:
|
|
105
|
+
"""점 n개인 신호의 기본 (입력 길이 L, 예측 길이 H, 간격): H는 L의 1/4, 학습 창은 MAX_TRAIN개 이하."""
|
|
106
|
+
L = int(min(96, max(8, n // 10)))
|
|
107
|
+
H = int(max(1, min(24, L // 4)))
|
|
108
|
+
stride = int(max(1, np.ceil((n * 0.8 - L - H) / MAX_TRAIN)))
|
|
109
|
+
return L, H, stride
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def make_forecast_dataset(series, L: int, H: int, stride: int = 1, test_ratio: float = 0.2, normalize: bool = True,
|
|
113
|
+
source: dict | None = None, column: str = "값", columns: list | None = None,
|
|
114
|
+
times=None, use_calendar: bool = True, time_column: str | None = None):
|
|
115
|
+
"""신호 하나 → 예측 Dataset (task "forecast", X는 정규화한 입력 창, y는 원래 단위의 다음 H개).
|
|
116
|
+
times(시각, 신호와 같은 길이)가 있고 use_calendar면 시각·요일 채널을 함께 넣음."""
|
|
117
|
+
from blocklearning.data import DataError, Dataset, Issue, seq_length
|
|
118
|
+
v = np.asarray(series, dtype=np.float64).ravel()
|
|
119
|
+
n = len(v)
|
|
120
|
+
if L < 2 or H < 1:
|
|
121
|
+
raise DataError([Issue(None, None, f"입력 길이 {L}·예측 길이 {H}이(가) 너무 짧음", "입력 길이 2 이상, 예측 길이 1 이상")])
|
|
122
|
+
cal, cal_names = calendar(times) if times is not None and use_calendar else (None, [])
|
|
123
|
+
cut = int(round(n * (1 - test_ratio)))
|
|
124
|
+
lo = max(0, cut - L)
|
|
125
|
+
Xtr, Ytr = window_channels(v[:cut], None if cal is None else cal[:, :cut], L, H, stride)
|
|
126
|
+
Xte, Yte = window_channels(v[lo:], None if cal is None else cal[:, lo:], L, H, stride)
|
|
127
|
+
if len(Xtr) < MIN_TRAIN or len(Xte) < 1:
|
|
128
|
+
need = (MIN_TRAIN - 1) * stride + L + H
|
|
129
|
+
raise DataError([Issue(None, None, f"점 {n}개로는 '지난 {L}개 → 다음 {H}개' 창이 모자람 (학습 창 {len(Xtr)}개, 시험 창 {len(Xte)}개)",
|
|
130
|
+
f"입력·예측 길이나 간격을 줄이세요 (학습 구간에 점이 {need}개 이상 필요)")])
|
|
131
|
+
mu, sd = (float(v[:cut].mean()), float(v[:cut].std()) or 1.0) if normalize else (0.0, 1.0)
|
|
132
|
+
src = dict(source or {})
|
|
133
|
+
src.update({"task": "forecast", "column": column, "L": int(L), "H": int(H), "stride": int(stride),
|
|
134
|
+
"calendar": bool(use_calendar)})
|
|
135
|
+
src.setdefault("normalize", normalize)
|
|
136
|
+
src.setdefault("test_ratio", test_ratio)
|
|
137
|
+
if cal_names:
|
|
138
|
+
src["channel_names"] = [column] + cal_names
|
|
139
|
+
extra = {"horizon": int(H), "stride": int(stride), "column": column, "columns": list(columns or [column]),
|
|
140
|
+
"n_points": int(n), "cut": int(cut), "has_times": times is not None, "calendar": cal_names,
|
|
141
|
+
"time_column": time_column}
|
|
142
|
+
k = len(cal_names) # 시각 채널은 이미 −1–1: 정규화하지 않음
|
|
143
|
+
mean = np.concatenate([np.full(L, mu), np.zeros(k * L)])
|
|
144
|
+
std = np.concatenate([np.full(L, sd), np.ones(k * L)])
|
|
145
|
+
return Dataset((Xtr - mean) / std, (Xte - mean) / std, Ytr, Yte, "forecast", [], seq_length(L, 1 + k), mean, std,
|
|
146
|
+
src, [], None, None, extra)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def metric(out: np.ndarray, y: np.ndarray) -> float:
|
|
150
|
+
"""다음 H개 전체를 펼쳐 R² (1이면 완벽, 0이면 늘 평균을 답하는 것과 같음)."""
|
|
151
|
+
o = np.asarray(out, dtype=float).reshape(len(y), -1)
|
|
152
|
+
y = np.asarray(y, dtype=float).reshape(len(y), -1)
|
|
153
|
+
ss = float(np.sum((y - y.mean()) ** 2))
|
|
154
|
+
return 1.0 - float(np.sum((o - y) ** 2)) / ss if ss > 0 else float("nan")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def naive(d, X: np.ndarray) -> np.ndarray:
|
|
158
|
+
"""단순 예측 (이보다 나아야 모델이 쓸모 있음): 입력이 H개 이상이면 지난 H개를 그대로 되풀이 (하루 주기 데이터에서
|
|
159
|
+
H = 24시간이면 '어제 같은 시각'), 아니면 마지막 값을 그대로 이어 씀."""
|
|
160
|
+
H, raw = d.extra["horizon"], history(d, X)
|
|
161
|
+
if raw.shape[1] >= H:
|
|
162
|
+
return raw[:, -H:]
|
|
163
|
+
return np.repeat(raw[:, -1:], H, axis=1)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def naive_name(d) -> str:
|
|
167
|
+
H = d.extra["horizon"]
|
|
168
|
+
return f"지난 {H}개를 그대로 되풀이" if d.length >= H else "마지막 값을 그대로"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def result(out: np.ndarray, d) -> dict:
|
|
172
|
+
"""결과 화면: MAE·RMSE(원래 단위)·단순 예측의 MAE·앞으로 몇 칸째인지에 따른 MAE·예시 창."""
|
|
173
|
+
y = np.asarray(d.y_test, dtype=float)
|
|
174
|
+
o = np.asarray(out, dtype=float).reshape(y.shape)
|
|
175
|
+
err = np.abs(o - y)
|
|
176
|
+
nv = np.abs(naive(d, d.X_test) - y)
|
|
177
|
+
k = len(y)
|
|
178
|
+
picks = sorted({int(round(i)) for i in np.linspace(0, k - 1, min(N_SAMPLES, k))})
|
|
179
|
+
raw = history(d, d.X_test)
|
|
180
|
+
r5 = lambda a: [round(float(x), 5) for x in a]
|
|
181
|
+
return {"mae": float(err.mean()), "rmse": float(np.sqrt(((o - y) ** 2).mean())), "naive_mae": float(nv.mean()),
|
|
182
|
+
"naive_name": naive_name(d),
|
|
183
|
+
"mae_by_step": r5(err.mean(0)), "naive_by_step": r5(nv.mean(0)),
|
|
184
|
+
"fc_samples": [{"index": i, "history": r5(raw[i]), "y": r5(y[i]), "pred": r5(o[i])} for i in picks]}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def load_forecast_csv(path: str, column=None, L=None, H=None, stride=None, normalize: bool = True,
|
|
188
|
+
test_ratio: float = 0.2, calendar: bool = True, **_) -> "Dataset":
|
|
189
|
+
"""긴 시계열 CSV (한 행 = 한 시점, 열 = 측정 항목) → 예측 Dataset. 값 열을 안 고르면 마지막 숫자 열.
|
|
190
|
+
입력·예측 길이·간격을 안 정하면 defaults(점 수). 빈 칸은 앞뒤 값으로 메움. 시각 열이 있으면 시각·요일 채널 (calendar)."""
|
|
191
|
+
from pathlib import Path
|
|
192
|
+
from blocklearning.data import DataError, Issue, _column_values, _numeric_columns, _read_table
|
|
193
|
+
names, rows = _read_table(path)
|
|
194
|
+
nums = _numeric_columns(names, rows)
|
|
195
|
+
if not nums:
|
|
196
|
+
raise DataError([Issue(None, None, "숫자 열이 없음", "한 행 = 한 시점, 열 = 측정값인 CSV를 고르세요 (시각 같은 글자 열은 있어도 됨)")])
|
|
197
|
+
col = column if column in nums else nums[-1]
|
|
198
|
+
v = _column_values(Path(path).name, names, rows, col)
|
|
199
|
+
dL, dH, ds = defaults(len(v))
|
|
200
|
+
L, H = int(L or dL), int(H or dH)
|
|
201
|
+
stride = int(stride or max(1, int(np.ceil((len(v) * (1 - test_ratio) - L - H) / MAX_TRAIN))))
|
|
202
|
+
tcol, times = find_times(names, rows, nums)
|
|
203
|
+
return make_forecast_dataset(v, L, H, stride, test_ratio, normalize, source={"path": str(path)}, column=col,
|
|
204
|
+
columns=nums, times=times, use_calendar=calendar, time_column=tcol)
|