import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline39.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_inline39.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)39.9.2 進捗とプロット
本書のプロットの大半は、1 組の座標軸に 1 本以上の曲線を描画する d2l.plot で作成されている。最初のセルでは、図の形式とサイズ(use_svg_display、set_figsize)、および軸のラベル・範囲・スケール(set_axes)を設定する。対数軸では、set_log_ticks がすべての主目盛りに 1 つの書式でラベルを付ける。
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)ProgressBoard(2.4 節)は、呼び出し元のスレッド上で描画する。show はすべての曲線を新しい図に描画し、ノートブック出力にある同じボードの前のフレームを置き換える。ヘッドレスの本書ビルドでは最後の呼び出しのみが描画されるため、実行済みノートブックにはボードごとに 1 つの図だけが記録される。損失は左軸に、正解率は右側の第 2 軸に配置され、その場合はどちらの曲線群も隠さないよう凡例がプロットの上方に移動する。検証の点および 1 点のみの曲線にはドットが付くため、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 は、d2l.train_2d(9.1 節)が返すような 2 次元の更新則の反復点を、目的関数 f の等高線上に描画する。表示範囲は開始点 \((-5, -2)\) と原点の最小点を網羅し、軌跡が収まるよう広がる。軌跡がいずれかの軸方向に発散しない限り、両軸は 1 つのスケールを共有する。
show_trace_2d は、d2l.train_2d(9.1 節)が返すような 2 次元の更新則の反復点を、目的関数 f の等高線上に描画する。表示範囲は開始点 \((-5, -2)\) と原点の最小点を網羅し、軌跡が収まるよう広がる。軌跡がいずれかの軸方向に発散しない限り、両軸は 1 つのスケールを共有する。
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 と同じ長さの 3 つの系列(推定値、およびその区間の下端と上端)に対応付ける。nan にするとその点は描画から除外される。kind='errorbar' では各推定値がバー付きのマーカとなり、バー同士が重なって隠れないよう各 x で系列が横並びに配置される。kind='band' では各系列が陰影付きの帯を伴う線になる。x には数値またはカテゴリ名を渡す。reference はランダム予測の正解率や 0 などの水平な破線を描画し、xscale は 'linear'、'log'、'log2' のいずれかを受け取る。系列 \(i\) は色 Ci で描画され、この関数は座標軸を返すため、呼び出し側で対応する線を追加できる。marks は第 2 の推定量など、系列にさらなる点を追加する。これは名前を matplotlib の書式('--'、'D')と系列ラベルごとの点 (xs, ys) に対応付けるもので、各系列の色で描画され、凡例には黒色で 1 回だけ記載される。
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 axes39.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 はシードごとに訓練ジェネレータを 1 回実行し、生成された曲線を形状 (seed, step, …) の 1 つの配列(plot_curves が受け取る入力形式)に積み重ねる。オフポリシーのエージェントはエピソードごとに 1 回記録を返し、完了するエピソード数はシードによって異なる。on_grid はそのようなエピソードごとの記録を環境ステップの共通グリッド上に揃えることで、同様に積み重ねてプロットできるようにする。
run_seeds はシードごとに訓練ジェネレータを 1 回実行し、生成された曲線を形状 (seed, step, …) の 1 つの配列(plot_curves が受け取る入力形式)に積み重ねる。オフポリシーのエージェントはエピソードごとに 1 回記録を返し、完了するエピソード数はシードによって異なる。on_grid はそのようなエピソードごとの記録を環境ステップの共通グリッド上に揃えることで、同様に積み重ねてプロットできるようにする。
強化学習エージェントの JAX 実装は、1 度に 1 つの状態に対して行動を選択し、バッチごとに長さが変わるバッチ上で更新する。コンパイル済みコードはネットワークの構造、入力の形状、およびオプティマイザをキーとして管理されるため、3 つのヘルパでコンパイル回数を少なく抑えている。forward_np はネットワーク構造ごとに 1 つの順伝播をコンパイルし、呼び出しのたびにネットワークの現在のパラメータを読み取るため、オプティマイザのステップで再コンパイルは不要である。_pad と _bucket はバッチを次の 2 のべき乗(少なくとも 64 行)までパディングするため、異なる長さのバッチ間でコンパイル済みの更新が再利用される。また、padded は 1 つのバッチに含まれる複数の配列をまとめてパディングし、実際の行を示すマスクを追加することで、更新時の平均計算からパディング部分を除外できるようにする。shared_adam は学習率ごとに 1 つの optax.adam を保持するため、同じ学習率で作成されたエージェントはコンパイル済みの更新を共有する。また、plain_sgd は一部の実験で Adam の代わりに用いる素の 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)39.9.4 画像スコア用の特徴ネットワーク
生成モデルを扱う各章では、小規模な CIFAR-10 分類器の特徴を用いて画像のスコアを算出する(16.5 節)。load_cifar10_arrays は \([-1, 1]\) にスケーリングされた CIFAR-10 の訓練画像とテスト画像をラベルとともに返す。FeatureCNN は、それぞれバッチ正規化、ReLU、\(2 \times 2\) 最大プーリングを備える 3 つの畳み込みブロックに、グローバル平均プーリングと線形ヘッドが続く分類器である。その features メソッドはプーリング後の特徴を返し、resolution 引数は最初に入力をリサイズするサイズを指定する(縮小時にはローパスフィルタをかける)。train_feature_cnn は、Adam とワンサイクルの学習率スケジュールを用い、ランダム水平反転および(任意の)ランダムシフトを加えてこのモデルを訓練する。
生成モデルを扱う各章では、小規模な CIFAR-10 分類器の特徴を用いて画像のスコアを算出する(16.5 節)。load_cifar10_arrays は \([-1, 1]\) にスケーリングされた CIFAR-10 の訓練画像とテスト画像をラベルとともに返す。FeatureCNN は、それぞれバッチ正規化、ReLU、\(2 \times 2\) 最大プーリングを備える 3 つの畳み込みブロックに、グローバル平均プーリングと線形ヘッドが続く分類器である。その features メソッドはプーリング後の特徴を返し、resolution 引数は最初に入力をリサイズするサイズを指定する(縮小時にはローパスフィルタをかける)。train_feature_cnn は、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()39.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 は、行列ごとに 1 つのパネルを割り当て、色付きセルのグリッドとして行列を描画する。引数の形状は(パネルの行数、パネルの列数、高さ、幅)である。デフォルトではすべてのパネルが 1 つのカラースケールと 1 つのカラーバーを共有するが、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_grad39.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_seq39.9.6.1 小規模な語彙における埋め込み勾配
埋め込み参照の勾配計算では、各位置における勾配をその位置のトークンに対応する行へと加算するが、XLA はこれらの加算をアトミック演算として実行する。テキストのミニバッチでは、スペースや e のバイトなど、ごく少数の高頻度トークンが数千もの位置を占める。同じ行への加算は互いに待ち状態となるため、GPU 上ではランダムなトークンの場合に比べて合計計算に数十倍の時間がかかることがある。最大 1,024 トークンまでの語彙に対して、Embed はトークンのワンホット行と勾配の 1 回の行列積として同じ合計を計算する。それ以外の点では 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)39.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 は 4 つすべてのフレームワークに存在する。PyTorch と JAX では evaluate_accuracy(model, batches) が 9.3 節 で定義されており、MXNet と TensorFlow のタブでは上述のレガシーな evaluate_accuracy(net, data_iter) が維持されている。