import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline27.9 유틸리티 함수 및 클래스
이 절은 책 전반에서 사용하는 유틸리티 함수와 클래스의 실제 구현을 담고 있습니다. #@save 표시가 붙은 셀은 d2l 패키지로 복사되어 어느 절에서든 d2l.plot, d2l.set_figsize 등으로 바로 호출할 수 있습니다.
import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inlineimport collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inlineimport collections
import inspect
import random
import sys
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline27.9.1 하이퍼파라미터 유틸리티
@d2l.add_to_class(d2l.HyperParameters)
def save_hyperparameters(self, ignore=None):
"""Save function arguments into instance attributes."""
ignore = [] if ignore is None else ignore
frame = inspect.currentframe().f_back
_, _, _, local_vars = inspect.getargvalues(frame)
self.hparams = {k:v for k, v in local_vars.items()
if k not in set(ignore+['self']) and not k.startswith('_')}
for k, v in self.hparams.items():
setattr(self, k, v)27.9.2 진행 상황 및 플롯 유틸리티
이 책에 등장하는 대부분의 플롯은 하나의 좌표축 위에 하나 이상의 곡선을 그리는 d2l.plot에서 만들어집니다. 첫 번째 셀은 그림의 출력 형식과 크기(use_svg_display, set_figsize), 그리고 축의 레이블·범위·스케일(set_axes)을 설정합니다. 로그 스케일 축에서는 set_log_ticks가 모든 주 눈금(major tick)을 일관된 형식으로 표시합니다.
def use_svg_display():
"""Use the svg format to display a plot in Jupyter."""
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5, 2.5)):
"""Set the figure size for matplotlib."""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
def set_log_ticks(axis):
"""Label all major ticks of a log axis in one format."""
lo, hi = axis.get_view_interval()
if 0 < lo and hi < 100 * lo: # Under two decades: ticks at 1, 2, 5
axis.set_major_locator(ticker.LogLocator(subs=(1, 2, 5)))
ticks = axis.get_major_locator().tick_values(lo, hi)
plain = all(1e-4 <= t < 1e5 for t in ticks if lo <= t <= hi)
def label(v, _):
if plain: # 0.001, 0.01, ..., 10000
return f'{v:g}'
m, k = f'{v:.3e}'.split('e') # 2.500e-05 -> '2.500', '-05'
m, power = f'{float(m):g}', f'10^{{{int(k)}}}' # '2.5', '10^{-5}'
return f'${power}$' if m == '1' else f'${m}\\times{power}$'
axis.set_major_formatter(ticker.FuncFormatter(label))
axis.set_minor_formatter(ticker.NullFormatter())
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend,
legend_loc=None):
"""Set the axes for matplotlib. legend_loc is a matplotlib legend
location, or 'outside' for beside the axes, clear of the curves."""
axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
axes.set_xscale(xscale), axes.set_yscale(yscale)
axes.set_xlim(xlim), axes.set_ylim(ylim)
for axis, scale in ((axes.xaxis, xscale), (axes.yaxis, yscale)):
if scale == 'log':
set_log_ticks(axis)
if legend and legend_loc == 'outside':
axes.legend(legend, loc='center left', bbox_to_anchor=(1, 0.5))
elif legend:
axes.legend(legend, loc=legend_loc) # None: matplotlib's best spot
axes.grid()plot 코드의 상당 부분은 다양한 형태의 입력을 곡선 리스트라는 통일된 형식으로 정규화하는 역할을 합니다.
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None,
legend_loc=None):
"""Plot data points."""
legend = [] if legend is None else legend
def has_one_axis(X): # True if X (tensor or list) has 1 axis
return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
and not hasattr(X[0], "__len__"))
if has_one_axis(X): X = [X]
if Y is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
if len(X) != len(Y):
X = X * len(Y)
set_figsize(figsize)
if axes is None:
axes = d2l.plt.gca()
axes.cla()
# Extend the formats with new colors so that no curve is dropped
fmts = list(fmts) + [f'C{i % 10}' + ('-', '--', '-.', ':')[i % 4]
for i in range(len(fmts), len(Y))]
for x, y, fmt in zip(X, Y, fmts):
axes.plot(x, y, fmt) if len(x) else axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend,
legend_loc)2.4절 의 ProgressBoard는 호출한 스레드에서 바로 그림을 그립니다. show는 모든 곡선을 새 그림으로 렌더링하고 노트북 출력에서 동일 보드의 직전 프레임을 교체합니다. 헤드리스(headless) 모드로 실행되는 책 빌드에서는 마지막 호출만 렌더링되므로 실행이 끝난 노트북에는 보드당 하나의 그림만 남습니다. 손실은 왼쪽 축에, 정확도는 오른쪽 보조 축에 그려지며, 두 축을 함께 쓸 때는 범례가 어느 곡선도 가리지 않도록 플롯 위쪽으로 이동합니다. 검증 지점과 점이 하나뿐인 곡선에는 원형 마커를 찍어 1에포크만 실행한 결과도 눈에 잘 보이게 합니다.
import os
from matplotlib.figure import Figure
@d2l.add_to_class(d2l.ProgressBoard)
def show(self, final=True):
"""Redraw all curves; the book build renders only the final call."""
if not self.display or (
not final and os.environ.get('D2L_NB_CAPTURE') == '1'):
return
d2l.use_svg_display()
fig = Figure(figsize=self.figsize)
self._plot(fig.add_subplot())
if self.handle is None:
self.handle = display.display(fig, display_id=True)
else:
self.handle.update(fig)
@d2l.add_to_class(d2l.ProgressBoard)
def _plot(self, ax):
"""Losses on the left axis, accuracies on a right one."""
acc_ax = None
for i, (label, (xs, ys)) in enumerate(self.data.items()):
target = ax
if label.endswith('acc'):
acc_ax = acc_ax or ax.twinx()
target = acc_ax
# Mark validation points, and any curve that has a single point
marked = label.startswith('val') or len(xs) == 1
target.plot(xs, ys, ('-', '--', '-.', ':')[i % 4], color=f'C{i % 10}',
marker='o' if marked else None, markersize=3,
clip_on=not marked, label=label)
ax.set_xlabel(self.xlabel), ax.set_ylabel(self.ylabel)
ax.set_xscale(self.xscale), ax.set_yscale(self.yscale)
if self.xlim: ax.set_xlim(self.xlim)
if self.ylim: ax.set_ylim(self.ylim)
if self.yscale == 'log': d2l.set_log_ticks(ax.yaxis)
if acc_ax is not None: acc_ax.set_ylabel('accuracy')
lines = list(ax.get_lines()) + list(acc_ax.get_lines() if acc_ax else [])
labels = [line.get_label() for line in lines]
if acc_ax is not None: # Above the axes: no curve of either axis is hidden
ax.legend(lines, labels, loc='lower center', ncol=len(lines),
bbox_to_anchor=(0.5, 1), frameon=False)
elif lines:
ax.legend(lines, labels)
ax.grid()show_trace_2d는 9.1절 의 d2l.train_2d가 반환하는 2차원 갱신 규칙의 반복 궤적을 목적 함수 f의 등고선 위에 그립니다. 표시 윈도는 시작점 \((-5, -2)\) 와 원점의 최솟값을 기본으로 포함하며 궤적이 넓어지면 그에 맞춰 자동으로 확장됩니다. 어느 한 축 방향으로 궤적이 발산하지 않는 한 두 축은 동일한 스케일을 공유합니다.
show_trace_2d는 9.1절 의 d2l.train_2d가 반환하는 2차원 갱신 규칙의 반복 궤적을 목적 함수 f의 등고선 위에 그립니다. 표시 윈도는 시작점 \((-5, -2)\) 와 원점의 최솟값을 기본으로 포함하며 궤적이 넓어지면 그에 맞춰 자동으로 확장됩니다. 어느 한 축 방향으로 궤적이 발산하지 않는 한 두 축은 동일한 스케일을 공유합니다.
def show_trace_2d(f, results):
"""Show the trace of 2D variables over the contours of f."""
x1s, x2s = zip(*[(float(a), float(b)) for a, b in results])
grids = [] # A window around start and minimum, widened to fit the trace
for (lo, hi), xs in zip([(-5.5, 1.0), (-3.0, 3.0)], (x1s, x2s)):
lo, hi = min(lo, min(xs) - 0.5), max(hi, max(xs) + 0.5)
grids.append(d2l.arange(lo, hi, (hi - lo) / 100))
x1, x2 = d2l.meshgrid(*grids, indexing='ij')
width, height = (float(g[-1] - g[0]) for g in grids)
equal = 0.25 < height / width < 4 # Equal scales unless the trace diverged
d2l.set_figsize((3, 2.8) if equal else (3.5, 2.5))
d2l.plt.contour(x1, x2, f(x1, x2), colors='0.6', linewidths=0.8)
d2l.plt.plot(x1s, x2s, '-o', color='C1', markersize=4)
d2l.plt.xlabel('$x_1$')
d2l.plt.ylabel('$x_2$')
if equal:
d2l.plt.gca().set_aspect('equal')def show_trace_2d(f, results):
"""Show the trace of 2D variables over the contours of f."""
x1s, x2s = zip(*[(float(a), float(b)) for a, b in results])
grids = [] # A window around start and minimum, widened to fit the trace
for (lo, hi), xs in zip([(-5.5, 1.0), (-3.0, 3.0)], (x1s, x2s)):
lo, hi = min(lo, min(xs) - 0.5), max(hi, max(xs) + 0.5)
grids.append(d2l.arange(lo, hi, (hi - lo) / 100))
x1, x2 = d2l.meshgrid(*grids, indexing='ij')
width, height = (float(g[-1] - g[0]) for g in grids)
equal = 0.25 < height / width < 4 # Equal scales unless the trace diverged
d2l.set_figsize((3, 2.8) if equal else (3.5, 2.5))
d2l.plt.contour(x1, x2, f(x1, x2), colors='0.6', linewidths=0.8)
d2l.plt.plot(x1s, x2s, '-o', color='C1', markersize=4)
d2l.plt.xlabel('$x_1$')
d2l.plt.ylabel('$x_2$')
if equal:
d2l.plt.gca().set_aspect('equal')plot_intervals는 부트스트랩 오차 막대가 달린 정확도처럼 추정치와 그 구간을 함께 그립니다. series는 각 레이블을 x와 길이가 같은 세 시퀀스(추정치, 구간 하한, 구간 상한)에 매핑하며 nan인 지점은 건너뜁니다. kind='errorbar'일 때는 각 추정치를 오차 막대가 달린 마커로 그리되 막대끼리 겹치지 않도록 각 x 위치에서 시리즈들을 나란히 비켜 배치하고, kind='band'일 때는 반투명 음영 띠가 둘린 실선으로 그립니다. x에는 수치나 범주 이름이 올 수 있습니다. reference는 무작위 추측 정확도나 0 같은 기준값을 점선 수평선으로 그리고, xscale은 'linear', 'log', 'log2'를 받습니다. 시리즈 \(i\) 는 색상 Ci로 그려지며 호출자가 색상을 맞춘 보조선 등을 덧붙일 수 있도록 좌표축 객체를 반환합니다. marks는 보조 추정량 같은 추가 점들을 덧그리는 인자로, 이름을 matplotlib 포맷('--', 'D') 및 시리즈 레이블별 좌표 (xs, ys)에 매핑하여 해당 시리즈 색상으로 그리고 범례에는 검은색으로 한 번만 등록합니다.
def plot_intervals(x, series, xlabel, ylabel, *, kind='errorbar',
reference=None, xscale='linear', axes=None, marks=None):
"""Estimates with intervals: `series` maps a label to (mean, lo, hi);
`marks` maps a name to (fmt, {label: (xs, ys)})."""
if kind not in ('errorbar', 'band') or xscale not in ('linear', 'log',
'log2'):
raise ValueError(f'unknown kind {kind!r} or xscale {xscale!r}')
x = np.asarray(x)
categorical = not np.issubdtype(x.dtype, np.number)
pos = np.arange(len(x), dtype=float) if categorical else x.astype(float)
logx = xscale != 'linear' and not categorical
# Side-by-side offsets, in the units in which the x-axis is even
to_axis, from_axis = (np.log, np.exp) if logx else (np.asarray,) * 2
gaps = np.diff(np.unique(to_axis(pos)))
width = 0.6 * (gaps.min() if len(gaps) else 1.0) / len(series)
if axes is None:
d2l.set_figsize()
axes = d2l.plt.gca()
for i, (label, (mean, lo, hi)) in enumerate(series.items()):
mean, lo, hi = (np.asarray(v, dtype=float) for v in (mean, lo, hi))
if not mean.shape == lo.shape == hi.shape == pos.shape:
raise ValueError(f'{label}: mean, lo and hi need {len(pos)} '
'values each')
err = np.stack([mean - lo, hi - mean])
if np.any(err < -1e-9): # nan (a missing point) passes
raise ValueError(f'{label}: an interval misses its estimate')
color = f'C{i % 10}'
if kind == 'band':
axes.plot(pos, mean, '-', color=color, label=label)
axes.fill_between(pos, lo, hi, color=color, alpha=0.2,
linewidth=0)
else:
at = from_axis(to_axis(pos) + (i - (len(series) - 1) / 2) * width)
axes.errorbar(at, mean, yerr=np.clip(err, 0, None), fmt='o',
color=color, markersize=4, capsize=3, label=label)
for name, (fmt, points) in (marks or {}).items():
for i, label in enumerate(series):
if label in points:
axes.plot(*points[label], fmt, color=f'C{i % 10}')
axes.plot([], [], fmt, color='black', label=name) # legend only
if reference is not None:
axes.axhline(reference, linestyle='--', color='black', linewidth=0.8)
if logx:
axes.set_xscale('log', base=2 if xscale == 'log2' else 10)
if categorical or logx: # One tick per x value
axes.set_xticks(pos, [str(v) if categorical else f'{v:g}' for v in x])
axes.xaxis.set_minor_locator(ticker.NullLocator())
if categorical and len(x) > 3: # Slanted names do not collide
axes.set_xticklabels(axes.get_xticklabels(), rotation=30, ha='right')
axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
if len(series) > 1 or marks:
axes.legend()
axes.grid(axis='y' if categorical else 'both') # No line through a bar
return axes27.9.3 강화 학습 유틸리티
def plot_curves(curves, xlabel, ylabel, smooth=1, reference=None,
ylim=None, x=None, xscale='linear', yscale='linear',
band='range'):
"""One panel per call. `curves` maps a label to an array of shape
[seed, step] (or [step] for a single seed); plots the seed median and a
shaded band over the seeds: min to max (`band='range'`) or the
interquartile range (`band='iqr'`, the better summary from five seeds
on). `smooth`, if greater than 1, replaces each point by the mean of the
`smooth` steps that end there, before the seed statistics; the first
`smooth - 1` steps lack a full window and are dropped. `x` gives the
position of each step (default 0, 1, 2, ...). `reference`, if given,
draws a dashed horizontal line; `ylim` fixes the y-axis range; `xscale`
and `yscale` take matplotlib's scale names, e.g. 'log'."""
set_figsize((6, 4))
for name, values in curves.items():
values = np.atleast_2d(values)
xs = np.arange(values.shape[1]) if x is None else np.asarray(x)
if smooth > 1:
kernel = np.ones(smooth) / smooth
values = np.stack([np.convolve(v, kernel, 'valid')
for v in values])
xs = xs[smooth - 1:] # each window sits at its last step
line, = plt.plot(xs, np.median(values, axis=0), label=name)
if values.shape[0] > 1:
lo, hi = ((values.min(axis=0), values.max(axis=0))
if band == 'range' else
np.percentile(values, [25, 75], axis=0))
plt.fill_between(xs, lo, hi, alpha=0.2, color=line.get_color())
if reference is not None:
plt.axhline(reference, linestyle='--', color='gray')
if ylim is not None:
plt.ylim(ylim)
plt.xscale(xscale)
plt.yscale(yscale)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
def plot_hist(samples, xlabel, ylabel, bins=60, vlines=()):
"""Overlaid histograms of `samples` (label -> values), dashed at `vlines`."""
set_figsize((6, 4))
for name, x in samples.items():
plt.hist(x, bins=bins, alpha=0.5, label=name)
for v in vlines:
plt.axvline(v, linestyle='--', color='black')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
def show_grid(desc, values, policy=None, titles=None,
diverging=False, fmt='{:.2f}'):
"""A gridworld in the style of the chapter's figures. Each cell is
shaded by `values` (white to blue, or with `diverging=True` red to blue
around zero, for differences) and shows its state index (top left), its
value (bottom left) and an arrow for the action of `policy`, if given.
Holes are grey and the goal green; S, H and G sit at the bottom right.
The grid shape is read from `desc` (e.g. `env.unwrapped.desc`).
`values` and `policy` may each be a single frame, shape (num_states,),
or a sequence of frames, shape (num_frames, num_states); `titles`, if
given, labels each frame."""
h, w = desc.shape
values = np.atleast_2d(values).reshape(-1, h * w)
if policy is not None:
policy = np.atleast_2d(policy).reshape(-1, h * w)
if diverging:
top = max(np.abs(values).max(), 1e-12)
cmap, norm = plt.get_cmap('RdBu'), plt.Normalize(-top, top)
else:
cmap = plt.get_cmap('Blues')
norm = plt.Normalize(min(0.0, values.min()),
max(values.max(), 1e-12))
move = {0: (-1, 0), 1: (0, 1), 2: (1, 0), 3: (0, -1)} # (dx, dy)
fig, axes = plt.subplots(1, len(values), squeeze=False,
figsize=(3.6 * len(values), 3.6))
for k, ax in enumerate(axes[0]):
for s in range(h * w):
y, x = divmod(s, w)
cell, v = desc[y, x].decode(), values[k, s]
fill = {'H': ('#565D66', 0.55), 'G': ('#2CA02C', 0.35)}.get(
cell, (cmap(norm(v)), 1.0))
ax.add_patch(plt.Rectangle((x, y), 1, 1, fc=fill[0],
alpha=fill[1], ec='black', lw=1.0))
shade = np.abs(norm(v) - 0.5) * 2 if diverging else norm(v)
ink = 'white' if cell == 'H' or (cell != 'G' and shade > 0.6) \
else 'black'
ax.text(x + 0.07, y + 0.07, str(s), ha='left', va='top',
fontsize=9, color=ink)
if cell not in 'HG' or np.abs(v) > 1e-9: # terminal: 0
ax.text(x + 0.07, y + 0.93, fmt.format(v), ha='left',
va='bottom', fontsize=10, color=ink)
if cell in 'SHG':
ax.text(x + 0.82, y + 0.80, cell, ha='center', va='center',
fontsize=13, fontweight='bold', color=ink)
if policy is not None and cell not in 'HG':
dx, dy = move[int(policy[k, s])]
ax.annotate('', xy=(x + 0.5 + 0.22 * dx, y + 0.45 + 0.22 * dy),
xytext=(x + 0.5 - 0.22 * dx,
y + 0.45 - 0.22 * dy),
arrowprops=dict(arrowstyle='-|>', color=ink,
lw=1.6, mutation_scale=14))
ax.set_xlim(0, w)
ax.set_ylim(h, 0)
ax.set_aspect('equal')
ax.axis('off')
if titles is not None:
ax.set_title(titles[k])
fig.tight_layout()
def run_seeds(train, num_seeds, **kwargs):
"""Run train(seed, **kwargs), a generator of curve points, per seed."""
return np.array([list(train(seed, **kwargs)) for seed in range(num_seeds)])
def on_grid(runs, grid, col, smooth=1):
"""Resample per-episode rows (env step, value, ...) onto an env-step
grid. For each run, drop the rows whose column `col` is NaN, average
the column over the last `smooth` episodes, and interpolate linearly at
the grid points; returns [run, grid point], the input of plot_curves."""
out = []
for r in runs:
r = np.asarray(r, dtype=float)
r = r[~np.isnan(r[:, col])]
v = np.convolve(r[:, col], np.ones(smooth) / smooth, 'valid')
out.append(np.interp(grid, r[smooth - 1:, 0], v))
return np.stack(out)
def plot_curves(curves, xlabel, ylabel, smooth=1, reference=None,
ylim=None, x=None, xscale='linear', yscale='linear',
band='range'):
"""One panel per call. `curves` maps a label to an array of shape
[seed, step] (or [step] for a single seed); plots the seed median and a
shaded band over the seeds: min to max (`band='range'`) or the
interquartile range (`band='iqr'`, the better summary from five seeds
on). `smooth`, if greater than 1, replaces each point by the mean of the
`smooth` steps that end there, before the seed statistics; the first
`smooth - 1` steps lack a full window and are dropped. `x` gives the
position of each step (default 0, 1, 2, ...). `reference`, if given,
draws a dashed horizontal line; `ylim` fixes the y-axis range; `xscale`
and `yscale` take matplotlib's scale names, e.g. 'log'."""
set_figsize((6, 4))
for name, values in curves.items():
values = np.atleast_2d(values)
xs = np.arange(values.shape[1]) if x is None else np.asarray(x)
if smooth > 1:
kernel = np.ones(smooth) / smooth
values = np.stack([np.convolve(v, kernel, 'valid')
for v in values])
xs = xs[smooth - 1:] # each window sits at its last step
line, = plt.plot(xs, np.median(values, axis=0), label=name)
if values.shape[0] > 1:
lo, hi = ((values.min(axis=0), values.max(axis=0))
if band == 'range' else
np.percentile(values, [25, 75], axis=0))
plt.fill_between(xs, lo, hi, alpha=0.2, color=line.get_color())
if reference is not None:
plt.axhline(reference, linestyle='--', color='gray')
if ylim is not None:
plt.ylim(ylim)
plt.xscale(xscale)
plt.yscale(yscale)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
def plot_hist(samples, xlabel, ylabel, bins=60, vlines=()):
"""Overlaid histograms of `samples` (label -> values), dashed at `vlines`."""
set_figsize((6, 4))
for name, x in samples.items():
plt.hist(x, bins=bins, alpha=0.5, label=name)
for v in vlines:
plt.axvline(v, linestyle='--', color='black')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
def show_grid(desc, values, policy=None, titles=None,
diverging=False, fmt='{:.2f}'):
"""A gridworld in the style of the chapter's figures. Each cell is
shaded by `values` (white to blue, or with `diverging=True` red to blue
around zero, for differences) and shows its state index (top left), its
value (bottom left) and an arrow for the action of `policy`, if given.
Holes are grey and the goal green; S, H and G sit at the bottom right.
The grid shape is read from `desc` (e.g. `env.unwrapped.desc`).
`values` and `policy` may each be a single frame, shape (num_states,),
or a sequence of frames, shape (num_frames, num_states); `titles`, if
given, labels each frame."""
h, w = desc.shape
values = np.atleast_2d(values).reshape(-1, h * w)
if policy is not None:
policy = np.atleast_2d(policy).reshape(-1, h * w)
if diverging:
top = max(np.abs(values).max(), 1e-12)
cmap, norm = plt.get_cmap('RdBu'), plt.Normalize(-top, top)
else:
cmap = plt.get_cmap('Blues')
norm = plt.Normalize(min(0.0, values.min()),
max(values.max(), 1e-12))
move = {0: (-1, 0), 1: (0, 1), 2: (1, 0), 3: (0, -1)} # (dx, dy)
fig, axes = plt.subplots(1, len(values), squeeze=False,
figsize=(3.6 * len(values), 3.6))
for k, ax in enumerate(axes[0]):
for s in range(h * w):
y, x = divmod(s, w)
cell, v = desc[y, x].decode(), values[k, s]
fill = {'H': ('#565D66', 0.55), 'G': ('#2CA02C', 0.35)}.get(
cell, (cmap(norm(v)), 1.0))
ax.add_patch(plt.Rectangle((x, y), 1, 1, fc=fill[0],
alpha=fill[1], ec='black', lw=1.0))
shade = np.abs(norm(v) - 0.5) * 2 if diverging else norm(v)
ink = 'white' if cell == 'H' or (cell != 'G' and shade > 0.6) \
else 'black'
ax.text(x + 0.07, y + 0.07, str(s), ha='left', va='top',
fontsize=9, color=ink)
if cell not in 'HG' or np.abs(v) > 1e-9: # terminal: 0
ax.text(x + 0.07, y + 0.93, fmt.format(v), ha='left',
va='bottom', fontsize=10, color=ink)
if cell in 'SHG':
ax.text(x + 0.82, y + 0.80, cell, ha='center', va='center',
fontsize=13, fontweight='bold', color=ink)
if policy is not None and cell not in 'HG':
dx, dy = move[int(policy[k, s])]
ax.annotate('', xy=(x + 0.5 + 0.22 * dx, y + 0.45 + 0.22 * dy),
xytext=(x + 0.5 - 0.22 * dx,
y + 0.45 - 0.22 * dy),
arrowprops=dict(arrowstyle='-|>', color=ink,
lw=1.6, mutation_scale=14))
ax.set_xlim(0, w)
ax.set_ylim(h, 0)
ax.set_aspect('equal')
ax.axis('off')
if titles is not None:
ax.set_title(titles[k])
fig.tight_layout()
def run_seeds(train, num_seeds, **kwargs):
"""Run train(seed, **kwargs), a generator of curve points, per seed."""
return np.array([list(train(seed, **kwargs)) for seed in range(num_seeds)])
def on_grid(runs, grid, col, smooth=1):
"""Resample per-episode rows (env step, value, ...) onto an env-step
grid. For each run, drop the rows whose column `col` is NaN, average
the column over the last `smooth` episodes, and interpolate linearly at
the grid points; returns [run, grid point], the input of plot_curves."""
out = []
for r in runs:
r = np.asarray(r, dtype=float)
r = r[~np.isnan(r[:, col])]
v = np.convolve(r[:, col], np.ones(smooth) / smooth, 'valid')
out.append(np.interp(grid, r[smooth - 1:, 0], v))
return np.stack(out)run_seeds는 시드마다 훈련 제너레이터를 한 번씩 실행하고 생성된 곡선들을 plot_curves가 기대하는 (seed, step, …) 형상의 단일 배열로 쌓습니다. 비활성 정책(off-policy) 에이전트는 에포크가 아니라 에피소드마다 결과를 보고하므로 시드별로 완료하는 에피소드 수가 달라지는데, on_grid가 이러한 에피소드별 기록을 공통 환경 스텝 격자 위로 보간하여 배열로 쌓고 플롯할 수 있게 해 줍니다.
run_seeds는 시드마다 훈련 제너레이터를 한 번씩 실행하고 생성된 곡선들을 plot_curves가 기대하는 (seed, step, …) 형상의 단일 배열로 쌓습니다. 비활성 정책(off-policy) 에이전트는 에포크가 아니라 에피소드마다 결과를 보고하므로 시드별로 완료하는 에피소드 수가 달라지는데, on_grid가 이러한 에피소드별 기록을 공통 환경 스텝 격자 위로 보간하여 배열로 쌓고 플롯할 수 있게 해 줍니다.
강화 학습 에이전트의 JAX 구현은 한 번에 상태 하나씩 행동하고 매번 길이가 달라지는 배치로 매개변수를 갱신합니다. 컴파일된 코드는 신경망 구조, 입력 형상, 옵티마이저를 키로 캐싱되므로 재컴파일 횟수를 줄이기 위해 세 가지 보조 도구를 둡니다. forward_np는 신경망 구조당 순전파 하나만 컴파일하고 호출할 때마다 현재 매개변수를 읽어 오므로 옵티마이저 스텝 이후에도 재컴파일이 필요 없습니다. _pad와 _bucket은 배치를 최소 64행 이상의 가장 가까운 2의 거듭제곱 길이로 패딩하여 길이가 다른 배치들 사이에서 컴파일된 갱신 함수를 재사용하며, padded는 한 배치에 속한 여러 배열을 함께 패딩하고 실제 유효 행을 가리키는 마스크를 덧붙여 갱신 시 평균 계산에서 패딩 행을 제외할 수 있게 합니다. shared_adam은 학습률당 하나의 optax.adam을 유지해 같은 학습률로 생성된 에이전트들이 컴파일된 갱신 함수를 공유하게 하며, 일부 실험에서 Adam 대신 쓰는 기본 확률적 경사 하강법(SGD)에 대해서도 plain_sgd가 같은 역할을 합니다.
def plain_sgd(net, lr):
"""A plain SGD optimizer over the parameters of `net`."""
return torch.optim.SGD(net.parameters(), lr=lr)
_forwards = {} # one compiled forward per net structure
import weakref
_splits = weakref.WeakKeyDictionary() # per net: its forward and variables
def forward_np(net, x):
"""net(x) for numpy x, as numpy, through one compiled forward per net
structure and input shape. The net is split once and its variables are
kept, so each call reads their current values: optimizer steps show up
without splitting again."""
if net not in _splits:
graph, state = nnx.split(net)
tree = jax.tree.structure(state)
if (graph, tree) not in _forwards:
_forwards[graph, tree] = jax.jit(lambda leaves, x: nnx.merge(
graph, jax.tree.unflatten(tree, leaves))(x))
_splits[net] = _forwards[graph, tree], jax.tree.leaves(
state, is_leaf=lambda v: isinstance(v, nnx.Variable))
forward, variables = _splits[net]
leaves = [v.get_raw_value() for v in variables]
return jax.tree.map(np.asarray, forward(leaves, x))
def _pad(x, size):
"""Zero-pad axis 0 of an array to `size` rows."""
x = np.asarray(x)
return np.pad(x, ((0, size - len(x)),) + ((0, 0),) * (x.ndim - 1))
def _bucket(n):
"""Padded batch length: the next power of two, at least 64, so that a
compiled pass is reused across batches of different lengths."""
return 1 << max(6, (n - 1).bit_length())
def padded(*arrays):
"""The arrays zero-padded along axis 0 to a shared bucket length, plus a
0/1 mask of the real rows, so that one compiled pass serves every batch
length."""
n = len(arrays[0])
size = _bucket(n)
mask = (np.arange(size) < n).astype(np.float32)
return (*(_pad(x, size) for x in arrays), mask)
_adams = {}
def shared_adam(lr):
"""One optax.adam per learning rate, shared by all agents: compiled
updates are keyed on the optimizer, so a new agent reuses the compiled
code instead of compiling it again."""
return _adams.setdefault(lr, optax.adam(lr))
_sgds = {}
def plain_sgd(net, lr):
"""A plain SGD optimizer over `net`, one optax.sgd per learning rate."""
return nnx.Optimizer(net, _sgds.setdefault(lr, optax.sgd(lr)),
wrt=nnx.Param)27.9.4 이미지 점수 산정용 특성 신경망
생성 모델 장들은 소규모 CIFAR-10 분류기의 특성 공간에서 생성 이미지의 품질 점수를 매깁니다(16.5절). load_cifar10_arrays는 \([-1, 1]\) 구간으로 스케일링된 CIFAR-10 훈련·테스트 이미지와 레이블을 반환합니다. FeatureCNN은 각각 배치 정규화, 정류 선형 유닛(ReLU), \(2 \times 2\) 최대 풀링으로 구성된 3개의 합성곱 블록 뒤에 전역 평균 풀링과 선형 헤드를 둔 분류기로, features 메서드가 풀링된 특성 벡터를 반환하며 resolution 인자는 입력을 먼저 리사이즈할 해상도를 지정합니다(축소 시 저역 통과 필터링 적용). train_feature_cnn은 무작위 수평 뒤집기와 선택적인 무작위 평행 이동 증강 위에서 원사이클(one-cycle) 학습률 스케줄을 적용한 Adam으로 이 분류기를 훈련합니다.
생성 모델 장들은 소규모 CIFAR-10 분류기의 특성 공간에서 생성 이미지의 품질 점수를 매깁니다(16.5절). load_cifar10_arrays는 \([-1, 1]\) 구간으로 스케일링된 CIFAR-10 훈련·테스트 이미지와 레이블을 반환합니다. FeatureCNN은 각각 배치 정규화, 정류 선형 유닛(ReLU), \(2 \times 2\) 최대 풀링으로 구성된 3개의 합성곱 블록 뒤에 전역 평균 풀링과 선형 헤드를 둔 분류기로, features 메서드가 풀링된 특성 벡터를 반환하며 resolution 인자는 입력을 먼저 리사이즈할 해상도를 지정합니다(축소 시 저역 통과 필터링 적용). train_feature_cnn은 무작위 수평 뒤집기와 선택적인 무작위 평행 이동 증강 위에서 원사이클(one-cycle) 학습률 스케줄을 적용한 Adam으로 이 분류기를 훈련합니다.
def load_cifar10_arrays():
"""CIFAR-10 on the GPU if there is one, pixel values scaled to [-1, 1].
Returns train_X, train_y, test_X, test_y."""
import pickle, warnings # not in the d2l library preamble
d2l.DATA_HUB['cifar10'] = (
'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
'874905e36347c8536514d0a26261acf3bff89bc7')
cifar_dir = d2l.download_extract('cifar10', 'cifar-10-batches-py')
def load_batch(name):
with open(f'{cifar_dir}/{name}', 'rb') as f, warnings.catch_warnings():
warnings.simplefilter('ignore') # legacy NumPy pickle format
batch = pickle.load(f, encoding='bytes')
X = torch.tensor(batch[b'data'], dtype=torch.float32)
return X.reshape(-1, 3, 32, 32) / 127.5 - 1, torch.tensor(
batch[b'labels'])
Xs, ys = zip(*[load_batch(f'data_batch_{i}') for i in range(1, 6)])
test_X, test_y = load_batch('test_batch')
device = d2l.try_gpu()
return (torch.cat(Xs).to(device), torch.cat(ys).to(device),
test_X.to(device), test_y.to(device))
class FeatureCNN(nn.Module):
"""Three conv blocks, global average pooling, and a linear head. Inputs
are first resized bilinearly to resolution x resolution."""
def __init__(self, feature_dim=128, resolution=32):
super().__init__()
self.resolution = resolution
widths = [3, 32, 64, feature_dim]
self.blocks = nn.ModuleList(
[nn.Sequential(nn.Conv2d(c_in, c_out, 3, padding=1),
nn.BatchNorm2d(c_out), nn.ReLU(),
nn.MaxPool2d(2))
for c_in, c_out in zip(widths[:-1], widths[1:])])
self.head = nn.Linear(feature_dim, 10)
def features(self, x):
if x.shape[-1] != self.resolution:
x = F.interpolate(x, size=(self.resolution, self.resolution),
mode='bilinear', antialias=True)
for block in self.blocks:
x = block(x)
return x.mean(dim=(2, 3))
def forward(self, x):
return self.head(self.features(x))
def train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003,
batch_size=256, shift=0, seed=0):
"""Train on random horizontal flips, plus random shifts of up to `shift`
pixels, with a one-cycle learning rate; end in evaluation mode."""
gen = torch.Generator(X.device).manual_seed(seed) # local random streams
gen_shift = torch.Generator().manual_seed(seed)
opt = torch.optim.Adam(cnn.parameters())
sched = torch.optim.lr_scheduler.OneCycleLR(
opt, max_lr, total_steps=num_epochs * (len(X) // batch_size),
cycle_momentum=False)
h, w = X.shape[2:]
cnn.train()
for epoch in range(num_epochs):
order = torch.randperm(len(X), device=X.device, generator=gen)
for i in range(0, len(order) - batch_size + 1, batch_size):
Xb, yb = X[order[i:i + batch_size]], y[order[i:i + batch_size]]
flip = torch.rand(len(Xb), 1, 1, 1, device=X.device,
generator=gen) < 0.5
Xb = torch.where(flip, Xb.flip(-1), Xb)
a, b = torch.randint(0, 2 * shift + 1, (2,),
generator=gen_shift).tolist()
Xb = F.pad(Xb, (shift,) * 4, mode='reflect')[..., a:a + h, b:b + w]
loss = F.cross_entropy(cnn(Xb), yb)
opt.zero_grad(), loss.backward(), opt.step(), sched.step()
cnn.eval()
def load_cifar10_arrays():
"""CIFAR-10 on the default device, pixel values scaled to [-1, 1].
Returns train_X, train_y, test_X, test_y."""
import pickle, warnings # not in the d2l library preamble
d2l.DATA_HUB['cifar10'] = (
'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
'874905e36347c8536514d0a26261acf3bff89bc7')
cifar_dir = d2l.download_extract('cifar10', 'cifar-10-batches-py')
def load_batch(name):
with open(f'{cifar_dir}/{name}', 'rb') as f, warnings.catch_warnings():
warnings.simplefilter('ignore') # legacy NumPy pickle format
batch = pickle.load(f, encoding='bytes')
X = batch[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
return (jnp.asarray(X, dtype=jnp.float32) / 127.5 - 1,
jnp.asarray(batch[b'labels']))
Xs, ys = zip(*[load_batch(f'data_batch_{i}') for i in range(1, 6)])
test_X, test_y = load_batch('test_batch')
return jnp.concatenate(Xs), jnp.concatenate(ys), test_X, test_y
class FeatureCNN(nnx.Module):
"""Three conv blocks, global average pooling, and a linear head. Inputs
are first resized bilinearly to resolution x resolution."""
def __init__(self, feature_dim=128, resolution=32, rngs=None):
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
self.resolution = resolution
widths = [3, 32, 64, feature_dim]
# Weights and biases from U(+-1/sqrt(fan_in)); with Flax's default
# initialization the same images score FDs about 15% lower
self.convs = nnx.List(
[d2l.Conv(c_in, c_out, (3, 3), padding='SAME', rngs=rngs)
for c_in, c_out in zip(widths[:-1], widths[1:])])
# Running averages decay 0.9; the variance is computed in two passes
self.norms = nnx.List([nnx.BatchNorm(c, momentum=0.9,
use_fast_variance=False,
rngs=rngs)
for c in widths[1:]])
self.head = d2l.Linear(feature_dim, 10, rngs=rngs)
def features(self, x):
if x.shape[1] != self.resolution:
x = jax.image.resize(
x, (x.shape[0], self.resolution, self.resolution, x.shape[3]),
method='bilinear')
for conv, norm in zip(self.convs, self.norms):
x = nnx.max_pool(nnx.relu(norm(conv(x))),
window_shape=(2, 2), strides=(2, 2))
return x.mean(axis=(1, 2))
def __call__(self, x):
return self.head(self.features(x))
def train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003,
batch_size=256, shift=0, seed=0):
"""Train on random horizontal flips, plus random shifts of up to `shift`
pixels, with a one-cycle learning rate; end in evaluation mode."""
schedule = optax.cosine_onecycle_schedule(
num_epochs * (len(X) // batch_size), max_lr)
opt = nnx.Optimizer(cnn, optax.adam(schedule), wrt=nnx.Param)
h, w = X.shape[1:3]
@nnx.jit
def step(cnn, opt, Xb, yb, key):
k1, k2 = jax.random.split(key)
flip = jax.random.bernoulli(k1, 0.5, (len(Xb), 1, 1, 1))
Xb = jnp.where(flip, Xb[:, :, ::-1], Xb)
a, b = jax.random.randint(k2, (2,), 0, 2 * shift + 1)
Xb = jnp.pad(Xb, ((0, 0), (shift, shift), (shift, shift), (0, 0)),
mode='reflect')
Xb = jax.lax.dynamic_slice(Xb, (0, a, b, 0), (len(Xb), h, w, 3))
def loss_fn(cnn):
return optax.softmax_cross_entropy_with_integer_labels(
cnn(Xb), yb).mean()
opt.update(cnn, nnx.grad(loss_fn)(cnn))
cnn.train()
key = jax.random.key(seed)
for epoch in range(num_epochs):
key, kp = jax.random.split(key)
order = jax.random.permutation(kp, len(X))
for i in range(0, len(order) - batch_size + 1, batch_size):
key, ka = jax.random.split(key)
idx = order[i:i + batch_size]
step(cnn, opt, X[idx], y[idx], ka)
cnn.eval()27.9.5 훈련 유틸리티
다음 레거시 보조 함수들은 하위 호환성을 위해 유지됩니다.
def load_array(data_arrays, batch_size, is_train=True):
"""Construct a PyTorch data iterator."""
dataset = torch.utils.data.TensorDataset(*data_arrays)
return torch.utils.data.DataLoader(dataset, batch_size, shuffle=is_train)
def sgd(params, lr, batch_size):
"""Minibatch stochastic gradient descent."""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
def get_dataloader_workers():
"""Use 4 processes to read the data."""
return 4
def load_data_fashion_mnist(batch_size, resize=None):
"""Download the Fashion-MNIST dataset and then load it into memory."""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True)
return (torch.utils.data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=get_dataloader_workers()),
torch.utils.data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=get_dataloader_workers()))
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""Compute the accuracy for a model on a dataset using a GPU."""
if isinstance(net, nn.Module):
net.eval() # Set the model to evaluation mode
if not device:
device = next(iter(net.parameters())).device
# No. of correct predictions, no. of predictions
metric = d2l.Accumulator(2)
with torch.no_grad():
for X, y in data_iter:
if isinstance(X, list):
# Required for BERT Fine-tuning (to be covered later)
X = [x.to(device) for x in X]
else:
X = X.to(device)
y = y.to(device)
metric.add(d2l.accuracy(net(X), y), d2l.size(y))
return metric[0] / metric[1]
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
"""Train a model with a GPU (defined in Chapter 6)."""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device)
net.to(device)
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# Sum of training loss, sum of training accuracy, no. of examples
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
optimizer.zero_grad()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
def load_array(data_arrays, batch_size, is_train=True):
"""Construct a TensorFlow data iterator."""
dataset = tf.data.Dataset.from_tensor_slices(data_arrays)
if is_train:
dataset = dataset.shuffle(buffer_size=1000)
dataset = dataset.batch(batch_size)
return dataset
def sgd(params, grads, lr, batch_size):
"""Minibatch stochastic gradient descent."""
for param, grad in zip(params, grads):
param.assign_sub(lr * grad / batch_size)
def load_data_fashion_mnist(batch_size, resize=None):
"""Download the Fashion-MNIST dataset and then load it into memory."""
mnist_train, mnist_test = tf.keras.datasets.fashion_mnist.load_data()
# Divide all numbers by 255 so that all pixel values are between
# 0 and 1, add a batch dimension at the last. And cast label to int32
process = lambda X, y: (tf.expand_dims(X, axis=3) / 255,
tf.cast(y, dtype='int32'))
resize_fn = lambda X, y: (
tf.image.resize_with_pad(X, resize, resize) if resize else X, y)
return (
tf.data.Dataset.from_tensor_slices(process(*mnist_train)).batch(
batch_size).shuffle(len(mnist_train[0])).map(resize_fn),
tf.data.Dataset.from_tensor_slices(process(*mnist_test)).batch(
batch_size).map(resize_fn))
class TrainCallback(tf.keras.callbacks.Callback):
"""A callback to visualize the training progress."""
def __init__(self, net, train_iter, test_iter, num_epochs, device_name):
self.timer = d2l.Timer()
self.animator = d2l.Animator(
xlabel='epoch', xlim=[1, num_epochs], legend=[
'train loss', 'train acc', 'test acc'])
self.net = net
self.train_iter = train_iter
self.test_iter = test_iter
self.num_epochs = num_epochs
self.device_name = device_name
def on_epoch_begin(self, epoch, logs=None):
self.timer.start()
def on_epoch_end(self, epoch, logs):
self.timer.stop()
test_acc = self.net.evaluate(
self.test_iter, verbose=0, return_dict=True)['accuracy']
metrics = (logs['loss'], logs['accuracy'], test_acc)
self.animator.add(epoch + 1, metrics)
if epoch == self.num_epochs - 1:
batch_size = next(iter(self.train_iter))[0].shape[0]
num_examples = batch_size * tf.data.experimental.cardinality(
self.train_iter).numpy()
print(f'loss {metrics[0]:.3f}, train acc {metrics[1]:.3f}, '
f'test acc {metrics[2]:.3f}')
print(f'{num_examples / self.timer.avg():.1f} examples/sec on '
f'{str(self.device_name)}')
def train_ch6(net_fn, train_iter, test_iter, num_epochs, lr, device):
"""Train a model with a GPU (defined in Chapter 6)."""
device_name = device._device_name
strategy = tf.distribute.OneDeviceStrategy(device_name)
with strategy.scope():
optimizer = tf.keras.optimizers.SGD(learning_rate=lr)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
net = net_fn()
net.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])
callback = TrainCallback(net, train_iter, test_iter, num_epochs,
device_name)
net.fit(train_iter, epochs=num_epochs, verbose=0, callbacks=[callback])
return net
def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b
def squared_loss(y_hat, y):
"""Squared loss."""
return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2
class ArrayDataLoader(d2l.ArrayLoader):
"""`d2l.ArrayLoader` that yields JAX arrays and also accepts a dataset.
Pass the arrays as positional arguments, or one dataset object with
`__len__` and `__getitem__` whose items are tuples of fields. Like
`d2l.ArrayLoader`, it keeps the last, partial minibatch unless
`drop_last=True`."""
def __init__(self, *args, batch_size=32, shuffle=False, drop_last=False):
if len(args) == 1 and not hasattr(args[0], 'shape'): # A dataset
items = [args[0][i] for i in range(len(args[0]))]
if isinstance(items[0], (tuple, list)):
args = tuple(np.array([item[j] for item in items])
for j in range(len(items[0])))
else:
args = (np.array(items),)
super().__init__(args, batch_size, shuffle=shuffle,
drop_last=drop_last)
def __iter__(self):
for batch in super().__iter__():
yield tuple(jnp.asarray(a) for a in batch)
def load_array(data_arrays, batch_size, is_train=True):
"""Minibatches of JAX arrays, reshuffled each pass if is_train."""
return d2l.ArrayDataLoader(*data_arrays, batch_size=batch_size,
shuffle=is_train)
class Animator:
"""For plotting data in animation."""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
class Accumulator:
"""For accumulating sums over `n` variables."""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
assert token in ('word', 'char'), 'Unknown token type: ' + token
return [line.split() if token == 'word' else list(line) for line in lines]
def truncate_pad(line, num_steps, padding_token):
"""Truncate or pad sequences."""
if len(line) > num_steps:
return line[:num_steps]
return line + [padding_token] * (num_steps - len(line))
def download_extract(name, folder=None):
"""Download and extract a zip/tar file."""
fname = download(name)
base_dir = os.path.dirname(fname)
data_dir, ext = os.path.splitext(fname)
target = os.path.join(base_dir, folder) if folder else data_dir
marker = fname + '.extracted'
if os.path.exists(marker):
return target
if ext == '.zip':
fp = zipfile.ZipFile(fname, 'r')
elif ext in ('.tar', '.gz'):
fp = tarfile.open(fname, 'r')
else:
assert False, 'Only zip/tar files can be extracted.'
fp.extractall(base_dir)
open(marker, 'w').close()
return target
def evaluate_loss(net, data_iter, loss):
"""Evaluate the loss of a model on the given dataset."""
metric = d2l.Accumulator(2)
for X, y in data_iter:
out = net(X)
y = d2l.reshape(y, out.shape)
l = loss(out, y)
metric.add(d2l.reduce_sum(l), d2l.size(l))
return metric[0] / metric[1]def load_array(data_arrays, batch_size, is_train=True):
"""Construct a Gluon data iterator."""
dataset = gluon.data.ArrayDataset(*data_arrays)
return gluon.data.DataLoader(dataset, batch_size, shuffle=is_train)
def sgd(params, lr, batch_size):
"""Minibatch stochastic gradient descent."""
for param in params:
param[:] = param - lr * param.grad / batch_size
def get_dataloader_workers():
"""Use 4 processes to read the data except for Windows."""
return 0 if sys.platform.startswith('win') else 4
def load_data_fashion_mnist(batch_size, resize=None):
"""Download the Fashion-MNIST dataset and then load it into memory."""
dataset = gluon.data.vision
trans = [dataset.transforms.ToTensor()]
if resize:
trans.insert(0, dataset.transforms.Resize(resize))
trans = dataset.transforms.Compose(trans)
mnist_train = dataset.FashionMNIST(train=True).transform_first(trans)
mnist_test = dataset.FashionMNIST(train=False).transform_first(trans)
return (gluon.data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=get_dataloader_workers()),
gluon.data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=get_dataloader_workers()))
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""Compute the accuracy for a model on a dataset using a GPU."""
if not device: # Query the first device where the first parameter is on
device = list(net.collect_params().values())[0].list_device()[0]
# No. of correct predictions, no. of predictions
metric = d2l.Accumulator(2)
for X, y in data_iter:
X, y = X.to_device(device), y.to_device(device)
metric.add(d2l.accuracy(net(X), y), d2l.size(y))
return metric[0] / metric[1]
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
"""Train a model with a GPU (defined in Chapter 6)."""
net.initialize(force_reinit=True, device=device, init=init.Xavier())
loss = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(),
'sgd', {'learning_rate': lr})
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# Sum of training loss, sum of training accuracy, no. of examples
metric = d2l.Accumulator(3)
for i, (X, y) in enumerate(train_iter):
timer.start()
# Here is the major difference from `d2l.train_epoch_ch3`
X, y = X.to_device(device), y.to_device(device)
with autograd.record():
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
trainer.step(X.shape[0])
metric.add(l.sum(), d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
def grad_clipping(net, theta):
"""Clip the gradient."""
if isinstance(net, gluon.Block):
params = [p.data() for p in net.collect_params().values()]
else:
params = net.params
norm = math.sqrt(sum((p.grad ** 2).sum() for p in params))
if norm > theta:
for param in params:
param.grad[:] *= theta / normdef evaluate_accuracy(net, data_iter):
"""Compute the accuracy for a model on a dataset."""
metric = Accumulator(2) # No. of correct predictions, no. of predictions
for X, y in data_iter:
metric.add(accuracy(net(X), y), d2l.size(y))
return metric[0] / metric[1]def evaluate_accuracy(net, data_iter):
"""Compute the accuracy for a model on a dataset."""
metric = Accumulator(2) # No. of correct predictions, no. of predictions
for X, y in data_iter:
metric.add(accuracy(net(X), y), d2l.size(y))
return metric[0] / metric[1]def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5,
cmap=None, vmin=None, vmax=None):
"""Plot a list of images (cmap colors single-channel images, on the
color scale from vmin to vmax if given)."""
figsize = (num_cols * scale, num_rows * scale)
_, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
axes = axes.flatten()
for i, (ax, img) in enumerate(zip(axes, imgs)):
try:
img = d2l.numpy(img)
except:
pass
ax.imshow(img, cmap=cmap, vmin=vmin, vmax=vmax)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if titles:
ax.set_title(titles[i])
return axesshow_heatmaps는 행렬 하나당 패널 하나씩 색상이 입혀진 격자 셀로 행렬들을 시각화하며, 인자 형상은 (패널 행 수, 패널 열 수, 높이, 너비)입니다. 기본 설정에서는 모든 패널이 단일 색상 스케일과 컬러바 하나를 공유하며, cbar='each'를 주면 패널마다 고유 스케일과 컬러바를 붙이고 cbar=False를 주면 컬러바를 생략합니다. 눈금은 정수 행·열 인덱스를 표시하며 xticklabels와 yticklabels로 토큰 이름 등을 붙일 수 있습니다. 3.3절 의 혼동 행렬과 10장 의 어텐션 가중치를 그릴 때 사용됩니다.
def show_heatmaps(matrices, xlabel, ylabel, titles=None,
figsize=(2.5, 2.5), cmap='Reds', cbar=True,
xticklabels=None, yticklabels=None):
"""Show heatmaps of matrices; cbar is True (shared), 'each' or False."""
d2l.use_svg_display()
matrices = d2l.numpy(matrices)
num_rows, num_cols, height, width = matrices.shape
fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
sharex=True, sharey=True, squeeze=False)
# All panels share one color scale (one norm) unless each gets its own
lims = {} if cbar == 'each' else dict(norm=d2l.plt.Normalize(
matrices.min(), matrices.max()))
for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):
for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):
pcm = ax.imshow(matrix, cmap=cmap, **lims)
if cbar == 'each':
fig.colorbar(pcm, ax=ax, shrink=0.6)
if i == num_rows - 1:
ax.set_xlabel(xlabel)
if j == 0:
ax.set_ylabel(ylabel)
if titles:
ax.set_title(titles[j])
# Shared axes: setting the ticks of one panel sets them for all
for axis, n, labels in ((ax.xaxis, width, xticklabels),
(ax.yaxis, height, yticklabels)):
if labels is None:
axis.set_major_locator(d2l.plt.MaxNLocator(
'auto', integer=True, steps=[1, 2, 2.5, 5, 10]))
else: # Named ticks; names along the x-axis read vertically
axis.set_ticks(range(n), labels,
rotation=90 if axis is ax.xaxis else 0)
if cbar is True:
fig.colorbar(pcm, ax=axes, shrink=0.6);def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b
def squared_loss(y_hat, y):
"""Squared loss."""
return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
#@tab pytorch, mxnet, tensorflow
class Animator:
"""For plotting data in animation."""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
# Incrementally plot multiple lines
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
# Use a lambda function to capture arguments
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
# Add multiple data points into the figure
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
#@tab pytorch, mxnet, tensorflow
class Accumulator:
"""For accumulating sums over `n` variables."""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
"""Compute the number of correct predictions."""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = d2l.argmax(y_hat, axis=1)
elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
# Binary classification with float scores (logits or probabilities):
# threshold at 0 (logits) to get class labels, then reshape to match y.
y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
cmp = d2l.astype(y_hat, y.dtype) == y
return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))
def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b
def squared_loss(y_hat, y):
"""Squared loss."""
return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
#@tab pytorch, mxnet, tensorflow
class Animator:
"""For plotting data in animation."""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
# Incrementally plot multiple lines
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
# Use a lambda function to capture arguments
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
# Add multiple data points into the figure
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
#@tab pytorch, mxnet, tensorflow
class Accumulator:
"""For accumulating sums over `n` variables."""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
"""Compute the number of correct predictions."""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = d2l.argmax(y_hat, axis=1)
elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
# Binary classification with float scores (logits or probabilities):
# threshold at 0 (logits) to get class labels, then reshape to match y.
y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
cmp = d2l.astype(y_hat, y.dtype) == y
return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))
def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b
def squared_loss(y_hat, y):
"""Squared loss."""
return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
#@tab pytorch, mxnet, tensorflow
class Animator:
"""For plotting data in animation."""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
# Incrementally plot multiple lines
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
# Use a lambda function to capture arguments
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
# Add multiple data points into the figure
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
#@tab pytorch, mxnet, tensorflow
class Accumulator:
"""For accumulating sums over `n` variables."""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
"""Compute the number of correct predictions."""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = d2l.argmax(y_hat, axis=1)
elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
# Binary classification with float scores (logits or probabilities):
# threshold at 0 (logits) to get class labels, then reshape to match y.
y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
cmp = d2l.astype(y_hat, y.dtype) == y
return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))import os
import requests
import zipfile
import tarfile
import hashlib
def download(url, folder='../data', sha1_hash=None):
"""Download a file to folder and return the local filepath."""
if not url.startswith('http'):
# For back compatibility
url, sha1_hash = DATA_HUB[url]
os.makedirs(folder, exist_ok=True)
fname = os.path.join(folder, url.split('/')[-1])
# Check if hit cache
if os.path.exists(fname) and sha1_hash:
sha1 = hashlib.sha1()
with open(fname, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
if sha1.hexdigest() == sha1_hash:
return fname
# Download
import tempfile
print(f'Downloading {fname} from {url}...')
r = requests.get(url, stream=True, verify=True)
fd, tmp = tempfile.mkstemp(dir=folder)
try:
with os.fdopen(fd, 'wb') as f:
f.write(r.content)
os.replace(tmp, fname)
except BaseException:
os.unlink(tmp)
raise
return fname
def extract(filename, folder=None):
"""Extract a zip/tar file into folder."""
import tempfile, shutil
base_dir = os.path.dirname(filename)
_, ext = os.path.splitext(filename)
assert ext in ('.zip', '.tar', '.gz'), 'Only support zip/tar files.'
opener = zipfile.ZipFile if ext == '.zip' else tarfile.open
if folder is None:
folder = base_dir
tmp = tempfile.mkdtemp(dir=folder)
try:
with opener(filename, 'r') as fp:
fp.extractall(tmp)
for name in os.listdir(tmp):
src = os.path.join(tmp, name)
dst = os.path.join(folder, name)
if os.path.isdir(dst):
shutil.rmtree(dst)
os.rename(src, dst)
finally:
shutil.rmtree(tmp, ignore_errors=True)def download_extract(name, folder=None):
"""Download and extract a zip/tar file."""
fname = download(name)
base_dir = os.path.dirname(fname)
data_dir, ext = os.path.splitext(fname)
target = os.path.join(base_dir, folder) if folder else data_dir
# Skip re-extraction if a completion marker exists (extracting many small
# files is slow and unnecessary when the archive is already unpacked).
marker = fname + '.extracted'
if os.path.exists(marker):
return target
if ext == '.zip':
fp = zipfile.ZipFile(fname, 'r')
elif ext in ('.tar', '.gz'):
fp = tarfile.open(fname, 'r')
else:
assert False, 'Only zip/tar files can be extracted.'
fp.extractall(base_dir)
open(marker, 'w').close()
return target
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
assert token in ('word', 'char'), 'Unknown token type: ' + token
return [line.split() if token == 'word' else list(line) for line in lines]
def download_extract(name, folder=None):
"""Download and extract a zip/tar file."""
fname = download(name)
base_dir = os.path.dirname(fname)
data_dir, ext = os.path.splitext(fname)
target = os.path.join(base_dir, folder) if folder else data_dir
# Skip re-extraction if a completion marker exists (extracting many small
# files is slow and unnecessary when the archive is already unpacked).
marker = fname + '.extracted'
if os.path.exists(marker):
return target
if ext == '.zip':
fp = zipfile.ZipFile(fname, 'r')
elif ext in ('.tar', '.gz'):
fp = tarfile.open(fname, 'r')
else:
assert False, 'Only zip/tar files can be extracted.'
fp.extractall(base_dir)
open(marker, 'w').close()
return target
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
assert token in ('word', 'char'), 'Unknown token type: ' + token
return [line.split() if token == 'word' else list(line) for line in lines]
def download_extract(name, folder=None):
"""Download and extract a zip/tar file."""
fname = download(name)
base_dir = os.path.dirname(fname)
data_dir, ext = os.path.splitext(fname)
target = os.path.join(base_dir, folder) if folder else data_dir
# Skip re-extraction if a completion marker exists (extracting many small
# files is slow and unnecessary when the archive is already unpacked).
marker = fname + '.extracted'
if os.path.exists(marker):
return target
if ext == '.zip':
fp = zipfile.ZipFile(fname, 'r')
elif ext in ('.tar', '.gz'):
fp = tarfile.open(fname, 'r')
else:
assert False, 'Only zip/tar files can be extracted.'
fp.extractall(base_dir)
open(marker, 'w').close()
return target
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
assert token in ('word', 'char'), 'Unknown token type: ' + token
return [line.split() if token == 'word' else list(line) for line in lines]def evaluate_loss(net, data_iter, loss):
"""Evaluate the loss of a model on the given dataset."""
metric = d2l.Accumulator(2) # Sum of losses, no. of examples
for X, y in data_iter:
out = net(X)
y = d2l.reshape(y, out.shape)
l = loss(out, y)
metric.add(d2l.reduce_sum(l), d2l.size(l))
return metric[0] / metric[1]def evaluate_loss(net, data_iter, loss):
"""Evaluate the loss of a model on the given dataset."""
metric = d2l.Accumulator(2) # Sum of losses, no. of examples
for X, y in data_iter:
l = loss(net(X), y)
metric.add(d2l.reduce_sum(l), d2l.size(l))
return metric[0] / metric[1]def evaluate_loss(net, data_iter, loss):
"""Evaluate the loss of a model on the given dataset."""
metric = d2l.Accumulator(2) # Sum of losses, no. of examples
for X, y in data_iter:
l = loss(net(X), y)
metric.add(d2l.reduce_sum(l), d2l.size(l))
return metric[0] / metric[1]def grad_clipping(net, theta):
"""Clip the gradient."""
if isinstance(net, nn.Module):
params = [p for p in net.parameters() if p.requires_grad]
else:
params = net.params
norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))
if norm > theta:
for param in params:
param.grad[:] *= theta / normdef grad_clipping(grads, theta):
"""Clip the gradient."""
theta = tf.constant(theta, dtype=tf.float32)
new_grad = []
for grad in grads:
if isinstance(grad, tf.IndexedSlices):
new_grad.append(tf.convert_to_tensor(grad))
else:
new_grad.append(grad)
norm = tf.math.sqrt(sum((tf.reduce_sum(grad ** 2)).numpy()
for grad in new_grad))
norm = tf.cast(norm, tf.float32)
if tf.greater(norm, theta):
for i, grad in enumerate(new_grad):
new_grad[i] = grad * theta / norm
else:
new_grad = new_grad
return new_grad27.9.6 시퀀스 및 어텐션 유틸리티
d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
'94646ad1522d915e7b0f9296181140edcf86a4f5')
def read_data_nmt():
"""Load the English-French dataset."""
data_dir = d2l.download_extract('fra-eng')
with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
return f.read()
def preprocess_nmt(text):
"""Preprocess the English-French dataset."""
def no_space(char, prev_char):
return char in set(',.!?') and prev_char != ' '
# Replace non-breaking space with space, and convert uppercase letters to
# lowercase ones
text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
# Insert space between words and punctuation marks
out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
for i, char in enumerate(text)]
return ''.join(out)
def tokenize_nmt(text, num_examples=None):
"""Tokenize the English-French dataset."""
source, target = [], []
for i, line in enumerate(text.split('\n')):
if num_examples and i > num_examples:
break
parts = line.split('\t')
if len(parts) == 2:
source.append(parts[0].split(' '))
target.append(parts[1].split(' '))
return source, target
def truncate_pad(line, num_steps, padding_token):
"""Truncate or pad sequences."""
if len(line) > num_steps:
return line[:num_steps] # Truncate
return line + [padding_token] * (num_steps - len(line)) # Pad
def build_array_nmt(lines, vocab, num_steps):
"""Transform text sequences of machine translation into minibatches."""
lines = [vocab[l] for l in lines]
lines = [l + [vocab['<eos>']] for l in lines]
array = d2l.tensor([truncate_pad(
l, num_steps, vocab['<pad>']) for l in lines])
valid_len = d2l.reduce_sum(
d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
return array, valid_len
def load_data_nmt(batch_size, num_steps, num_examples=600):
"""Return the iterator and the vocabularies of the translation dataset."""
text = preprocess_nmt(read_data_nmt())
source, target = tokenize_nmt(text, num_examples)
src_vocab = d2l.Vocab(source, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
tgt_vocab = d2l.Vocab(target, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
data_iter = d2l.load_array(data_arrays, batch_size)
return data_iter, src_vocab, tgt_vocab
d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
'94646ad1522d915e7b0f9296181140edcf86a4f5')
def read_data_nmt():
"""Load the English-French dataset."""
data_dir = d2l.download_extract('fra-eng')
with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
return f.read()
def preprocess_nmt(text):
"""Preprocess the English-French dataset."""
def no_space(char, prev_char):
return char in set(',.!?') and prev_char != ' '
# Replace non-breaking space with space, and convert uppercase letters to
# lowercase ones
text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
# Insert space between words and punctuation marks
out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
for i, char in enumerate(text)]
return ''.join(out)
def tokenize_nmt(text, num_examples=None):
"""Tokenize the English-French dataset."""
source, target = [], []
for i, line in enumerate(text.split('\n')):
if num_examples and i > num_examples:
break
parts = line.split('\t')
if len(parts) == 2:
source.append(parts[0].split(' '))
target.append(parts[1].split(' '))
return source, target
def truncate_pad(line, num_steps, padding_token):
"""Truncate or pad sequences."""
if len(line) > num_steps:
return line[:num_steps] # Truncate
return line + [padding_token] * (num_steps - len(line)) # Pad
def build_array_nmt(lines, vocab, num_steps):
"""Transform text sequences of machine translation into minibatches."""
lines = [vocab[l] for l in lines]
lines = [l + [vocab['<eos>']] for l in lines]
array = d2l.tensor([truncate_pad(
l, num_steps, vocab['<pad>']) for l in lines])
valid_len = d2l.reduce_sum(
d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
return array, valid_len
def load_data_nmt(batch_size, num_steps, num_examples=600):
"""Return the iterator and the vocabularies of the translation dataset."""
text = preprocess_nmt(read_data_nmt())
source, target = tokenize_nmt(text, num_examples)
src_vocab = d2l.Vocab(source, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
tgt_vocab = d2l.Vocab(target, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
data_iter = d2l.load_array(data_arrays, batch_size)
return data_iter, src_vocab, tgt_vocab
d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
'94646ad1522d915e7b0f9296181140edcf86a4f5')
def read_data_nmt():
"""Load the English-French dataset."""
data_dir = d2l.download_extract('fra-eng')
with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
return f.read()
def preprocess_nmt(text):
"""Preprocess the English-French dataset."""
def no_space(char, prev_char):
return char in set(',.!?') and prev_char != ' '
# Replace non-breaking space with space, and convert uppercase letters to
# lowercase ones
text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
# Insert space between words and punctuation marks
out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
for i, char in enumerate(text)]
return ''.join(out)
def tokenize_nmt(text, num_examples=None):
"""Tokenize the English-French dataset."""
source, target = [], []
for i, line in enumerate(text.split('\n')):
if num_examples and i > num_examples:
break
parts = line.split('\t')
if len(parts) == 2:
source.append(parts[0].split(' '))
target.append(parts[1].split(' '))
return source, target
def truncate_pad(line, num_steps, padding_token):
"""Truncate or pad sequences."""
if len(line) > num_steps:
return line[:num_steps] # Truncate
return line + [padding_token] * (num_steps - len(line)) # Pad
def build_array_nmt(lines, vocab, num_steps):
"""Transform text sequences of machine translation into minibatches."""
lines = [vocab[l] for l in lines]
lines = [l + [vocab['<eos>']] for l in lines]
array = d2l.tensor([truncate_pad(
l, num_steps, vocab['<pad>']) for l in lines])
valid_len = d2l.reduce_sum(
d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
return array, valid_len
def load_data_nmt(batch_size, num_steps, num_examples=600):
"""Return the iterator and the vocabularies of the translation dataset."""
text = preprocess_nmt(read_data_nmt())
source, target = tokenize_nmt(text, num_examples)
src_vocab = d2l.Vocab(source, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
tgt_vocab = d2l.Vocab(target, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
data_iter = d2l.load_array(data_arrays, batch_size)
return data_iter, src_vocab, tgt_vocabdef sequence_mask(X, valid_len, value=0):
"""Mask irrelevant entries in sequences."""
maxlen = X.size(1)
mask = torch.arange((maxlen), dtype=torch.float32,
device=X.device)[None, :] < valid_len[:, None]
X[~mask] = value
return X
class MaskedSoftmaxCELoss(nn.CrossEntropyLoss):
"""The softmax cross-entropy loss with masks."""
# `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
# `label` shape: (`batch_size`, `num_steps`)
# `valid_len` shape: (`batch_size`,)
def __init__(self):
super().__init__(reduction='none')
def forward(self, pred, label, valid_len):
weights = torch.ones_like(label)
weights = sequence_mask(weights, valid_len)
unweighted_loss = super().forward(pred.permute(0, 2, 1), label)
weighted_loss = (unweighted_loss * weights).mean(dim=1)
return weighted_loss
def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
"""Train a model for sequence to sequence."""
def xavier_init_weights(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.GRU:
for param in m._flat_weights_names:
if "weight" in param:
nn.init.xavier_uniform_(m._parameters[param])
net.apply(xavier_init_weights)
net.to(device)
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
loss = MaskedSoftmaxCELoss()
net.train()
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[10, num_epochs])
for epoch in range(num_epochs):
timer = d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for batch in data_iter:
optimizer.zero_grad()
X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch]
bos = torch.tensor([tgt_vocab['<bos>']] * Y.shape[0],
device=device).reshape(-1, 1)
dec_input = d2l.concat([bos, Y[:, :-1]], 1) # Teacher forcing
Y_hat, _ = net(X, dec_input, X_valid_len)
l = loss(Y_hat, Y, Y_valid_len)
l.sum().backward() # Make the loss scalar for `backward`
d2l.grad_clipping(net, 1)
num_tokens = Y_valid_len.sum()
optimizer.step()
with torch.no_grad():
metric.add(l.sum(), num_tokens)
if (epoch + 1) % 10 == 0:
animator.add(epoch + 1, (metric[0] / metric[1],))
print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
f'tokens/sec on {str(device)}')
def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
device, save_attention_weights=False):
"""Predict for sequence to sequence."""
# Set `net` to eval mode for inference
net.eval()
src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
src_vocab['<eos>']]
enc_valid_len = torch.tensor([len(src_tokens)], device=device)
src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
# Add the batch axis
enc_X = torch.unsqueeze(
torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)
enc_outputs = net.encoder(enc_X, enc_valid_len)
dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
# Add the batch axis
dec_X = torch.unsqueeze(torch.tensor(
[tgt_vocab['<bos>']], dtype=torch.long, device=device), dim=0)
output_seq, attention_weight_seq = [], []
for _ in range(num_steps):
Y, dec_state = net.decoder(dec_X, dec_state)
# We use the token with the highest prediction likelihood as input
# of the decoder at the next time step
dec_X = Y.argmax(dim=2)
pred = dec_X.squeeze(dim=0).type(torch.int32).item()
# Save attention weights (to be covered later)
if save_attention_weights:
attention_weight_seq.append(net.decoder.attention_weights)
# Once the end-of-sequence token is predicted, the generation of the
# output sequence is complete
if pred == tgt_vocab['<eos>']:
break
output_seq.append(pred)
return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq
def sequence_mask(X, valid_len, value=0):
"""Mask irrelevant entries in sequences."""
maxlen = X.shape[1]
mask = tf.range(start=0, limit=maxlen, dtype=tf.float32)[
None, :] < tf.cast(valid_len[:, None], dtype=tf.float32)
if len(X.shape) == 3:
return tf.where(tf.expand_dims(mask, axis=-1), X, value)
else:
return tf.where(mask, X, value)
class MaskedSoftmaxCELoss(tf.keras.losses.Loss):
"""The softmax cross-entropy loss with masks."""
def __init__(self, valid_len):
super().__init__(reduction='none')
self.valid_len = valid_len
# `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
# `label` shape: (`batch_size`, `num_steps`)
# `valid_len` shape: (`batch_size`,)
def call(self, label, pred):
weights = tf.ones_like(label, dtype=tf.float32)
weights = sequence_mask(weights, self.valid_len)
label_one_hot = tf.one_hot(label, depth=pred.shape[-1])
unweighted_loss = tf.keras.losses.CategoricalCrossentropy(
from_logits=True, reduction='none')(label_one_hot, pred)
weighted_loss = tf.reduce_mean((unweighted_loss*weights), axis=1)
return weighted_loss
def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
"""Train a model for sequence to sequence."""
optimizer = tf.keras.optimizers.Adam(learning_rate=lr)
animator = d2l.Animator(xlabel="epoch", ylabel="loss",
xlim=[10, num_epochs])
for epoch in range(num_epochs):
timer = d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for batch in data_iter:
X, X_valid_len, Y, Y_valid_len = [x for x in batch]
bos = tf.reshape(tf.constant([tgt_vocab['<bos>']] * Y.shape[0]),
shape=(-1, 1))
dec_input = tf.concat([bos, Y[:, :-1]], 1) # Teacher forcing
with tf.GradientTape() as tape:
Y_hat, _ = net(X, dec_input, X_valid_len, training=True)
l = MaskedSoftmaxCELoss(Y_valid_len)(Y, Y_hat)
gradients = tape.gradient(l, net.trainable_variables)
gradients = d2l.grad_clipping(gradients, 1)
optimizer.apply_gradients(zip(gradients, net.trainable_variables))
num_tokens = tf.reduce_sum(Y_valid_len).numpy()
metric.add(tf.reduce_sum(l), num_tokens)
if (epoch + 1) % 10 == 0:
animator.add(epoch + 1, (metric[0] / metric[1],))
print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
f'tokens/sec on {str(device._device_name)}')
def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
save_attention_weights=False):
"""Predict for sequence to sequence."""
src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
src_vocab['<eos>']]
enc_valid_len = tf.constant([len(src_tokens)])
src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
# Add the batch axis
enc_X = tf.expand_dims(src_tokens, axis=0)
enc_outputs = net.encoder(enc_X, enc_valid_len, training=False)
dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
# Add the batch axis
dec_X = tf.expand_dims(tf.constant([tgt_vocab['<bos>']]), axis=0)
output_seq, attention_weight_seq = [], []
for _ in range(num_steps):
Y, dec_state = net.decoder(dec_X, dec_state, training=False)
# We use the token with the highest prediction likelihood as input
# of the decoder at the next time step
dec_X = tf.argmax(Y, axis=2)
pred = tf.squeeze(dec_X, axis=0)
# Save attention weights
if save_attention_weights:
attention_weight_seq.append(net.decoder.attention_weights)
# Once the end-of-sequence token is predicted, the generation of the
# output sequence is complete
if pred == tgt_vocab['<eos>']:
break
output_seq.append(pred.numpy())
return ' '.join(tgt_vocab.to_tokens(tf.reshape(output_seq, shape = -1).numpy().tolist())), attention_weight_seq
class MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss):
"""The softmax cross-entropy loss with masks."""
# `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
# `label` shape: (`batch_size`, `num_steps`)
# `valid_len` shape: (`batch_size`,)
def forward(self, pred, label, valid_len):
# `weights` shape: (`batch_size`, `num_steps`, 1)
weights = mnp.expand_dims(mnp.ones_like(label), axis=-1)
weights = npx.sequence_mask(weights, valid_len, True, axis=1)
return super(MaskedSoftmaxCELoss, self).forward(pred, label, weights)
def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
"""Train a model for sequence to sequence."""
net.initialize(init.Xavier(), force_reinit=True, device=device)
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': lr})
loss = MaskedSoftmaxCELoss()
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[10, num_epochs])
for epoch in range(num_epochs):
timer = d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for batch in data_iter:
X, X_valid_len, Y, Y_valid_len = [
x.to_device(device) for x in batch]
bos = mnp.array([tgt_vocab['<bos>']] * Y.shape[0],
device=device).reshape(-1, 1)
dec_input = d2l.concat([bos, Y[:, :-1]], 1) # Teacher forcing
with autograd.record():
Y_hat, _ = net(X, dec_input, X_valid_len)
l = loss(Y_hat, Y, Y_valid_len)
l.backward()
d2l.grad_clipping(net, 1)
num_tokens = Y_valid_len.sum()
trainer.step(num_tokens)
metric.add(l.sum(), num_tokens)
if (epoch + 1) % 10 == 0:
animator.add(epoch + 1, (metric[0] / metric[1],))
print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
f'tokens/sec on {str(device)}')
def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
device, save_attention_weights=False):
"""Predict for sequence to sequence."""
src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
src_vocab['<eos>']]
enc_valid_len = mnp.array([len(src_tokens)], device=device)
src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
# Add the batch axis
enc_X = mnp.expand_dims(mnp.array(src_tokens, device=device), axis=0)
enc_outputs = net.encoder(enc_X, enc_valid_len)
dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
# Add the batch axis
dec_X = mnp.expand_dims(
mnp.array([tgt_vocab['<bos>']], device=device), axis=0)
output_seq, attention_weight_seq = [], []
for _ in range(num_steps):
Y, dec_state = net.decoder(dec_X, dec_state)
# We use the token with the highest prediction likelihood as input
# of the decoder at the next time step
dec_X = Y.argmax(axis=2)
pred = dec_X.squeeze(axis=0).astype('int32').item()
# Save attention weights (to be covered later)
if save_attention_weights:
attention_weight_seq.append(net.decoder.attention_weights)
# Once the end-of-sequence token is predicted, the generation of the
# output sequence is complete
if pred == tgt_vocab['<eos>']:
break
output_seq.append(pred)
return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq27.9.6.1 소규모 어휘 사전을 위한 임베딩 그레이디언트
임베딩 조회의 그레이디언트는 각 위치의 그레이디언트를 해당 위치 토큰의 임베딩 행에 더하며, XLA는 이 덧셈을 원자적 연산(atomic operation)으로 수행합니다. 그런데 텍스트 미니배치에서는 공백 문자나 e의 바이트처럼 빈도가 높은 소수의 토큰이 수천 개의 위치를 차지합니다. 같은 행에 몰리는 원자적 덧셈들이 서로 순서를 기다리게 되면서 GPU에서는 무작위 토큰일 때보다 수십 배나 오래 걸릴 수 있습니다. 어휘 사전 크기가 최대 1,024 토큰 이하일 때 Embed는 동일한 합산을 토큰 원-핫 행렬과 그레이디언트의 단일 행렬 곱셈으로 계산합니다. 그 외의 동작은 일반 nnx.Embed와 동일하며, 이 책의 JAX 모델들은 토큰 테이블에 이 클래스를 사용합니다.
@jax.custom_vjp
def embedding_rows(table, X):
"""The rows X of table."""
return table[X]
def _embedding_rows_fwd(table, X):
return table[X], (table, X)
def _embedding_rows_bwd(residuals, grad):
"""Gradient of the table: the one-hot rows of X times the gradients."""
table, X = residuals
one_hot = jax.nn.one_hot(X, len(table), dtype=grad.dtype)
return jnp.einsum('...v,...d->vd', one_hot, grad,
precision='highest').astype(table.dtype), None
embedding_rows.defvjp(_embedding_rows_fwd, _embedding_rows_bwd)
class Embed(nnx.Embed):
"""nnx.Embed whose gradient is a matrix product for small vocabularies."""
def __call__(self, X):
table = self.embedding[...]
if len(table) > 1024: # A one-hot row would cost too much
return super().__call__(X)
return embedding_rows(table, X).astype(self.dtype or table.dtype)27.9.7 프레임워크 지원 범위에 관한 참고
이 절의 레거시 보조 함수들(train_ch6, train_seq2seq, predict_seq2seq, MaskedSoftmaxCELoss)은 이번 판에서 도입된 통합 d2l.Trainer 클래스 이전의 초기 D2L 구현과 호환성을 맞추기 위해 유지된 것이며 JAX용으로는 제공되지 않습니다. JAX 탭을 읽는 독자의 경우 해당 장들은 처음부터 끝까지 d2l.Trainer.fit(model, data)를 사용하며, 배치별 세부 로직은 Trainer.fit_epoch와 그 옆에 정의된 @d2l.add_to_class 확장에 구현되어 있습니다. evaluate_accuracy는 네 프레임워크 모두에 존재합니다. PyTorch와 JAX는 9.3절 에서 evaluate_accuracy(model, batches)를 정의하며, MXNet과 TensorFlow 탭은 위 코드의 레거시 evaluate_accuracy(net, data_iter)를 유지합니다.