はじめに
インストールと基本
TensorFlow 2.x は、デフォルトでイーガーに実行します(演算が通常の Python のように即座に実行されます)。CUDA GPU が可視か検証するには、tf.config.list_physical_devices('GPU') を使いましょう。GPU 対応のためには、Linux/Windows では [and-cuda] のエクストラを、Apple Silicon では tensorflow-metal をインストールします。TF 2.x は、Keras を tf.keras としてマージしました — ほとんどのワークフローで使われる高レベル API です。
# install TensorFlow (CPU)
pip install tensorflow
# with GPU support on Linux/Windows (CUDA-enabled)
pip install tensorflow[and-cuda]
import tensorflow as tf
# check version and devices
print(tf.__version__)
print("GPU:", tf.config.list_physical_devices('GPU'))
# eager execution is on by default in TF2
print(tf.executing_eagerly()) # True最初のテンソル
tf.constant は不変のテンソルを作り、tf.zeros / tf.ones / tf.random.* はよくあるパターンを作ります。すべてのテンソルには、shape、dtype、rank があります。.numpy() は NumPy へ戻す橋渡しです — GPU 上では、同期コピーが引き起こされ得ます。パフォーマンスを壊すサイレントなアップキャストを避けるため、明示的な dtype(ML では float32 がデフォルト)を優先しましょう。
import tensorflow as tf
# constants are immutable
x = tf.constant([[1, 2], [3, 4]])
y = tf.zeros((3, 3))
z = tf.random.normal((2, 3), mean=0.0, stddev=1.0)
print(x.shape, x.dtype) # (2, 2) int32
print(tf.reduce_sum(x)) # tf.Tensor(10, shape=(), dtype=int32)
# numpy interop is zero-copy when possible
print(x.numpy()) # array([[1, 2], [3, 4]])イーガー実行と勾配
イーガー実行により、TF が通常の Python のようにデバッグ可能になります — print、pdb、トレースバックがすべて機能します。GradientTape は、監視されたテンソル上の順伝播の演算を記録するため(tf.Variable は自動的に監視されます)、tape.gradient が微分を計算できます。カスタムの訓練ループの基礎がこれです。テープはデフォルトで単回利用です。複数回 gradient を呼ぶには、persistent=True を使いましょう。
import tensorflow as tf
a = tf.constant(3.0)
b = tf.constant(4.0)
print(a * b + 1) # tf.Tensor(13.0, ...)
# GradientTape records ops for automatic differentiation
with tf.GradientTape() as tape:
tape.watch(a)
y = a ** 2 + b # y = a^2 + b, dy/da = 2a
grad = tape.gradient(y, a)
print(grad) # tf.Tensor(6.0, ...) (= 2*3)tf.function とグラフ
@tf.function は、Python の関数をポータブルで最適化可能な TensorFlow グラフに変換します — GPU 上でずっと速く、分散に必要です。関数は入力シグネチャごとに 1 回トレースされるため、内側で Python の副作用やデータ依存の Python 制御フローを避けましょう(tf.cond / tf.while_loop を使わないと、再トレースされます)。変数は関数の外で一度だけ作るか、同じ名前の tf.Variable を再利用しましょう。
import tensorflow as tf
@tf.function # traces a graph; runs in graph mode after first call
def train_step(x, y):
with tf.GradientTape() as tape:
preds = x * w + b
loss = tf.reduce_mean((preds - y) ** 2)
grads = tape.gradient(loss, [w, b])
optimizer.apply_gradients(zip(grads, [w, b]))
return loss
w = tf.Variable(0.1)
b = tf.Variable(0.0)
optimizer = tf.keras.optimizers.SGD(0.01)
# first call builds the graph (slower); subsequent calls are fast
loss = train_step(tf.constant([1., 2.]), tf.constant([2., 4.]))混合精度
混合精度は float16 で計算しますが、float32 のマスター コピーを保つため、Tensor Core GPU(Volta+)で 2〜3 倍のスループットと半分 のメモリが得られます。「mixed_float16」のポリシーは、アンダーフローを防ぐためロススケーリングを自動的に扱います。数値安定性のために、出力層を float32 に強制しましょう。計算能力 >= 7.0 が必要です。古い GPU では遅くなり得ます。
import tensorflow as tf
# enable mixed precision: compute in float16, store in float32
tf.keras.mixed_precision.set_global_policy('mixed_float16')
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', dtype='float32'),
tf.keras.layers.Dense(10, activation='softmax', dtype='float32')
])
# loss scaling is automatic with mixed_float16 policy
print(tf.keras.mixed_precision.global_policy())テンソル
tf.constant
tf.constant は不変のテンソルを作ります — 要素への代入はできません。訓練可能なテンソルには tf.Variable を使いましょう。tf.random.normal/uniform は、再現性のために seed 引数を受け付け、tf.random.set_seed(42) はプログラム全体を再現可能にします。驚きを避けるため、多次元の作成には(int でなく)shape のタプルを使いましょう。
import tensorflow as tf
a = tf.constant([1, 2, 3])
b = tf.constant([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)
zeros = tf.zeros((2, 3))
ones = tf.ones((3, 3))
eye = tf.eye(3)
full = tf.fill((2, 3), 7.0)
arange = tf.range(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = tf.linspace(0.0, 1.0, 5)
rand = tf.random.uniform((2, 3))
randn = tf.random.normal((2, 3))
# constants are immutable: a[0] = 5 -> TypeErrortf.Variable
tf.Variable は、モデルのパラメータとオプティマイザの状態に使われる可変のテンソルラッパーです。assign / assign_add / assign_sub がその場で更新し — 通常の Python の代入(w = w + 1)は新しいテンソルを作り、ミューテートしません。変数は GradientTape により自動的に監視されますが、tf.constant は tape.watch() を明示的にしなければなりません。変数は、それを使う演算と同じ デバイスに保ちましょう。
import tensorflow as tf
w = tf.Variable(0.1, dtype=tf.float32)
W = tf.Variable(tf.random.normal((3, 4)))
b = tf.Variable(tf.zeros((4,)))
# read value
print(w.numpy()) # 0.1
# update value
w.assign(0.5)
w.assign_add(0.1) # w += 0.1
w.assign_sub(0.05)
# assign in place on a slice
W[0, 0].assign(99.0)
# watched by GradientTape automatically
with tf.GradientTape() as tape:
y = w ** 2
grad = tape.gradient(y, w) # 2wテンソルの演算
ほとんどの数学は NumPy を映し返します:tf.reduce_sum / reduce_mean / reduce_max は、np.sum/mean/max に相当します。特定の次元を還元するには axis= を、ブロードキャストのために rank を保つには keepdims=True を使いましょう。tf.matmul と @ 演算子は行列乗算を行います(入力が 3D+ のときバッチ化されます)。reshape は可能なときビューを返し、TF で transpose は常にコピーを返します。
import tensorflow as tf
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
b = tf.constant([[5.0, 6.0], [7.0, 8.0]])
a + b; a - b; a * b; a / b # element-wise
c = tf.matmul(a, b) # matrix multiply
c = a @ b # equivalent
tf.reduce_sum(a) # sum of all
tf.reduce_sum(a, axis=0) # sum along axis 0
tf.reduce_mean(a, axis=1) # mean along axis 1
tf.reduce_max(a, axis=1)
tf.reduce_sum(a, axis=1, keepdims=True)
x = tf.range(12)
y = tf.reshape(x, (3, 4))
t = tf.transpose(y) # shape (4, 3)インデックスとスライス
TF は、イーガーモードと tf.function の内側で、NumPy 風のスライスをサポートします。マスクが True の要素を抽出するのが、tf.boolean_mask(フラット化されます)です。デフォルトで軸 0 に沿って選択するのが、tf.gather です(ファンシーインデックスのようです)。ベクトル化された三項演算であるのが、tf.where(cond, x, y) で — cond が True のとき x から、さもなければ y から選びます。代入には、tf.tensor_scatter_nd_update か tf.Variable を使いましょう。
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
x[0] # first row
x[1, 2] # element (1,2) -> 6
x[:, 1] # second column
x[0:2] # first two rows
x[:, ::2] # every other column
# boolean mask
mask = x > 4
sel = tf.boolean_mask(x, mask) # tensor([5, 6, 7, 8, 9])
# gather by indices
idx = tf.constant([0, 2])
rows = tf.gather(x, idx) # rows 0 and 2
# where: select from two tensors
tf.where(x > 4, x, tf.zeros_like(x))Ragged と Sparse のテンソル
Ragged テンソルは、パディングなしで可変長のシーケンスを保存します — 異なる長さの NLP のバッチに最適です。Sparse テンソルは、非ゼロのインデックスと値だけを保存するため、高度にスパースなデータ(推薦、グラフ)でメモリを節約します。ほとんどの演算にはスパース対応のバリアントがあり、演算が必要なときだけ dense へ変換しましょう。埋め込みの参照のために矩形へパディングするのが、tf.RaggedTensor.to_tensor() です。
import tensorflow as tf
# ragged: variable-length sequences
ragged = tf.ragged.constant([[1, 2, 3], [4], [5, 6]])
print(ragged.shape) # (3, None)
ragged.to_tensor() # pad to (3, 3)
# sparse: mostly-zero tensors
indices = [[0, 0], [1, 2], [2, 1]]
values = [1.0, 2.0, 3.0]
sparse = tf.sparse.SparseTensor(
indices=indices, values=values, dense_shape=[3, 3])
dense = tf.sparse.to_dense(sparse)
sp_sum = tf.sparse.reduce_sum(sparse)
sp_matmul = tf.sparse.sparse_dense_matmul(sparse, tf.eye(3))ブロードキャストと数学
ブロードキャストは、小さい次元のテンソルを大きいものに合わせ伸ばし、要素ごとに作用します。TF のクランプであるのが、clip_by_value です。要素ごとのものが、tf.maximum/minimum で(次元を還元する tf.reduce_max/min とは異なります)。軸に沿った累積の和/積を作るのが、cumsum/cumprod で — カスタム層での累積メトリックとプレフィックス和のアルゴリズムに有用です。
import tensorflow as tf
# broadcasting follows NumPy rules
a = tf.constant([[1.0, 2.0, 3.0]]) # shape (1, 3)
b = tf.constant([[10.0], [20.0]]) # shape (2, 1)
c = a + b # shape (2, 3)
tf.abs(x); tf.sqrt(x); tf.exp(x); tf.log(x)
tf.square(x); tf.pow(x, 3)
tf.maximum(a, b); tf.minimum(a, b)
tf.clip_by_value(x, 0.0, 1.0)
tf.norm(x) # L2 norm
tf.norm(x, ord=1) # L1 norm
tf.cumsum(tf.range(5)) # [0, 1, 3, 6, 10]
tf.cumprod(tf.range(1, 5)) # [1, 2, 6, 24]Keras モデル
Sequential API
Sequential は、最も簡単な Keras のモデルです — 各層の出力が次を養う、線形のパイプラインです。input_shape はバッチ次元を含みません(可変バッチには None を使います)。layer の shape とパラメータ数を表示するのが、model.summary() です。input_shape を渡さないと、モデルは最初の fit/フォワードの呼び出しで遅延構築されます — より早く検査するには、build() を明示的に呼びましょう。
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax'),
])
model.summary()
# build later with input_shape (or first call)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10))
model.build((None, 784)) # None = variable batchFunctional API
Functional API は、層が分岐、マージ、スキップできるようにします — 非線形なもの(ResNet、マルチ入力/出力、シアメスネット)には必須です。Input のテンソルを定義し、層を呼び出すことで連鎖させ、inputs/outputs を Model へ渡しましょう。結果のモデルは、fit/predict において Sequential と同一に振る舞います。きれいな保存とサービングのシグネチャのために、inputs/outputs に名前を付けましょう。
import tensorflow as tf
inputs = tf.keras.Input(shape=(784,), name='img')
x = tf.keras.layers.Dense(128, activation='relu')(inputs)
x = tf.keras.layers.Dropout(0.5)(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
outputs = tf.keras.layers.Dense(10, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs, name='mlp')
# multi-input / multi-output
img_in = tf.keras.Input(shape=(224, 224, 3))
meta_in = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(img_in)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.concatenate([x, meta_in])
out = tf.keras.layers.Dense(1, activation='sigmoid')(x)
model = tf.keras.Model([img_in, meta_in], out)モデルのサブクラス化
tf.keras.Model のサブクラス化は、(PyTorch のような)フォワードの完全な制御を与えます。__init__ で層を定義し、call(inputs, training=) を実装します。training フラグが、dropout と BatchNorm の挙動を切り替えます。サブクラス化はより柔軟ですが、Functional API の一部の利点を失います:検査/プロットが難しく、入力 shape の推論が自動でなく、直列化も厄介です。ほとんどのアーキテクチャには Functional を優先し、研究のモデルにはサブクラス化を。
import tensorflow as tf
class MLP(tf.keras.Model):
def __init__(self, hidden=128, num_classes=10):
super().__init__()
self.dense1 = tf.keras.layers.Dense(hidden, activation='relu')
self.drop = tf.keras.layers.Dropout(0.5)
self.dense2 = tf.keras.layers.Dense(hidden, activation='relu')
self.out = tf.keras.layers.Dense(num_classes, activation='softmax')
def call(self, inputs, training=False):
x = self.dense1(inputs)
x = self.drop(x, training=training)
x = self.dense2(x)
return self.out(x)
model = MLP(hidden=64)
model.build((None, 784))
model.summary()モデルのコンパイル
compile は、fit の前にオプティマイザ、損失、メトリックを結線します。文字列(「adam」、「mse」)は対応するクラスへのショートカットです。カスタムのハイパーパラメータのためには、オブジェクトを渡しましょう。マルチ出力のモデルのためには、出力名を損失へマッピングする辞書を渡します。tf.function のトレースを無効化するのが、run_eagerly=True で、pdb と print が使えます — デバッグに極めて有用ですが、遅いです。
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
loss_weights={'cls': 1.0, 'box': 0.5},
)
# explicit objects (more control)
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name='acc')],
run_eagerly=False, # debug mode: run without graph
)モデルのサマリーとプロット
summary() は、出力 shape とパラメータ数付きの層ごとのテーブルを表示します — shape のバグを見つける最速の方法です。視覚的なグラフを保存するのが、plot_model です(pydot と Graphviz が必要です)。serializable な dict を返すのが、get_config で、アーキテクチャが重みなしで再構築できます — model.to_json() と Keras の保存形式が使うものです。Functional のモデルでは、config がアーキテクチャを完全に捉えます。サブクラス化されたモデルでは、get_config を自分で実装しなければなりません。
model.summary()
print(model.layers)
print(model.inputs, model.outputs)
# plot architecture (needs pydot + graphviz)
tf.keras.utils.plot_model(
model, to_file='model.png', show_shapes=True,
show_layer_names=True, rankdir='TB',
)
print(f"{model.count_params():,} params")
config = model.get_config()
new_model = tf.keras.Model.from_config(config)モデル内の前処理
前処理をモデルの内側に置くと(Rescaling、拡張の Keras 層)、配備可能になります:同じ SavedModel が、推論で生の画像を受け付け、別の前処理のステップが不要です。Keras の前処理の層は、GPU 上と tf.function の内側で走るため速いです。訓練専用の拡張のためには、fit で training=True を設定しましょう。そうすれば、推論で層は非アクティブです。Rescaling(1./255) は、uint8 [0,255] の画像を float [0,1] へ変換します。
import tensorflow as tf
# preprocessing as part of the model (deployable)
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(224, 224, 3)),
tf.keras.layers.Rescaling(1./255),
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.1),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
# ...
])
# the model now includes preprocessing, so inference needs raw images層
Dense 層
Dense は全結合層です:y = activation(xW + b) です。重みの shape は (in_features, out_features) で — PyTorch の転置です。kernel_initializer のデフォルトは Glorot/Xavier の一様で、tanh/sigmoid に良く、ReLU 系には「he_normal」を使いましょう。kernel_regularizer 経由で L2 の正則化を加えます。transformers でのデフォルトの活性化が、GELU です。
import tensorflow as tf
dense = tf.keras.layers.Dense(
units=64, activation='relu', use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=tf.keras.regularizers.l2(1e-4),
)
x = tf.random.normal((4, 128))
y = dense(x) # shape (4, 64)
print(dense.kernel.shape) # (128, 64)
print(dense.bias.shape) # (64,)
dense = tf.keras.layers.Dense(64, activation=tf.nn.gelu)Conv2D 層
TF/Keras は、デフォルトで NHWC(channels-last)を使います — PyTorch の NCHW と逆です。padding='same' は、出力の空間サイズ = 入力サイズ / ストライドになるようパディングし、「valid」はパディングなしを意味します。入力チャネルごとに 1 つのフィルタを適用するのが、DepthwiseConv2D です(MobileNet で使われます)。アップサンプルするのが、Conv2DTranspose です(セグメンテーションのデコーダで使われます)。カーネルの shape は、(kH, kW, in_channels, filters) です。
import tensorflow as tf
conv = tf.keras.layers.Conv2D(
filters=32, kernel_size=3, strides=(1, 1),
padding='same', activation='relu', use_bias=True,
)
x = tf.random.normal((4, 28, 28, 3)) # NHWC
out = conv(x)
print(out.shape) # (4, 28, 28, 32) with padding='same'
dw = tf.keras.layers.DepthwiseConv2D(3, padding='same', activation='relu')
up = tf.keras.layers.Conv2DTranspose(32, 3, strides=2, padding='same')再帰層(LSTM/GRU)
RNN の入力 shape は、(batch, timesteps, features) です。RNN を積むときや seq2seq のモデルには、return_sequences=True が必要で、sequence-to-vector には False です。順 方向と逆方向の出力を連結し、出力サイズを倍にするのが、Bidirectional です。recurrent_dropout は便利ですが遅いです(cuDNN の加速がありません)— 代わりに、入力への素の dropout を優先しましょう。
import tensorflow as tf
lstm = tf.keras.layers.LSTM(units=128, return_sequences=False)
x = tf.random.normal((4, 10, 64)) # (batch, time, features)
out = lstm(x) # (4, 128)
# stacked LSTM needs return_sequences=True
model = tf.keras.Sequential([
tf.keras.layers.LSTM(128, return_sequences=True, input_shape=(10, 64)),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(10),
])
gru = tf.keras.layers.GRU(128)
bi = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64))
out = bi(x) # shape (4, 128) — 64 * 2Dropout と正則化
Dropout は、共適応を防ぐため訓練中にユニットをランダムにゼロにします — 推論では自動的に無効です(training=False です)。特徴マップ全体を落とすのが、SpatialDropout2D で、conv ネットにはより良いです。最もよくある正則化が、L2(重み減衰)です。特徴軸上(サンプルごと)で正規化するのが、LayerNormalization で、バッチ軸上で正規化する BatchNorm と異なります — transformers と RNN に好まれます。
import tensorflow as tf
drop = tf.keras.layers.Dropout(0.5)
x = tf.random.normal((4, 10))
y = drop(x, training=True) # training=True activates dropout
tf.keras.layers.SpatialDropout2D(0.5) # drop entire feature maps
tf.keras.layers.GaussianDropout(0.5)
tf.keras.layers.AlphaDropout(0.5)
# weight regularization
tf.keras.layers.Dense(64,
kernel_regularizer=tf.keras.regularizers.l2(1e-4),
activity_regularizer=tf.keras.regularizers.l1(1e-5))
norm = tf.keras.layers.LayerNormalization()Batch Normalization
BatchNormalization は、チャネルごとに活性化を正規化し、推論のための EMA の実行統計を保ちます。NHWC のために最後の(チャネル)軸を正規化するのが、axis=-1 です。BN を conv の後、活性化の前に置き、BN の beta がシフトを扱うため、conv のバイアスを無効化しましょう(use_bias=False)。実行統計がデータを追う速さを制御するのが、momentum で — 高い値(0.99)がより安定です。BN は、(training フラグにより)訓練と推論で異なって振る舞います。
import tensorflow as tf
bn = tf.keras.layers.BatchNormalization(
axis=-1, momentum=0.99, epsilon=1e-3,
)
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, padding='same', use_bias=False),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.ReLU(),
])
print(len(bn.weights)) # 4
print(len(bn.trainable_weights)) # 2カスタム層
カスタムの演算を構築するには、Layer をサブクラス化しましょう。__init__ でなく build()(入力 shape と共に一度呼ばれます)で重みを定義すれば、層が入力サイズに適応します。層が直列化されリロードできるよう、get_config() を実装しましょう。add_weight は、テンソルを Keras のトラッキングに登録します(weights に現れ、保存され、デバイスへ動かされます)。ステートレスな変換のためには、build() を省き、call() をオーバーライドするだけでも構いません。
import tensorflow as tf
class Linear(tf.keras.layers.Layer):
def __init__(self, units=32, **kwargs):
super().__init__(**kwargs)
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer='glorot_uniform', trainable=True, name='w')
self.b = self.add_weight(
shape=(self.units,), initializer='zeros', trainable=True, name='b')
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
config = super().get_config()
config.update({'units': self.units})
return config
layer = Linear(64)
out = layer(tf.random.normal((4, 10)))損失
BinaryCrossentropy
BinaryCrossentropy は、二値のタスクかマルチラベル(各クラスが独立)のためのものです。モデルが生のロジットを出力するなら、from_logits=True を渡しましょう — sigmoid + BCE を別々に適用するより数値的に安全です。不均衡を扱うため、正の例を重くするのが、pos_weight です。C クラスのマルチラベルの問題のためには、ターゲットの shape が 0/1 の (N, C) で、予測は (N, C) の確率かロジットです。
import tensorflow as tf
bce = tf.keras.losses.BinaryCrossentropy(from_logits=False)
y_true = tf.constant([[1.0], [0.0], [1.0], [0.0]])
y_pred = tf.constant([[0.9], [0.1], [0.8], [0.2]])
loss = bce(y_true, y_pred)
# from_logits=True is more numerically stable
bce_logits = tf.keras.losses.BinaryCrossentropy(from_logits=True)
logits = tf.constant([[2.0], [-2.0], [1.5], [-1.5]])
loss = bce_logits(y_true, logits)
bce = tf.keras.losses.BinaryCrossentropy(
from_logits=True, pos_weight=tf.constant([5.0]))CategoricalCrossentropy
CategoricalCrossentropy は one-hot のターゲットを期待し、SparseCategoricalCrossentropy は整数のクラスインデックスを期待します(多くのクラスでよりメモリ効率が良いです)。モデルが softmax で終わらないときは、必ず from_logits=True を渡しましょう — 数値安定性のために log-sum-exp のトリックを使います。ラベルスムージングには、CategoricalCrossentropy(label_smoothing=0.1) を使いましょう — 分類と NLP の強い正則化です。
import tensorflow as tf
# one-hot labels
cce = tf.keras.losses.CategoricalCrossentropy(from_logits=False)
y_true = tf.constant([[0, 1, 0], [1, 0, 0]], dtype=tf.float32)
y_pred = tf.constant([[0.1, 0.8, 0.1], [0.7, 0.2, 0.1]])
loss = cce(y_true, y_pred)
# integer labels -> use sparse version
scce = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
y_true_int = tf.constant([1, 0])
logits = tf.constant([[1.0, 3.0, 0.5], [2.5, 0.2, 0.1]])
loss = scce(y_true_int, logits)MSE と回帰の損失
MSE は大きな誤差を二次的に罰します(外れ値に敏感で)、MAE は線形です。ゼロ近くでは MSE のように、遠くでは MAE のように振る舞うのが、Huber で — 物体検出の回帰のデフォルトです。似ていますがどこでも 2 回微分可能なのが、LogCosh で、二階の勾配が必要なときに有用です。すべてデフォルトでバッチ上の平均へ還元されます。サンプルごとの損失のためには、reduction=tf.keras.losses.Reduction.NONE で上書きしましょう。
import tensorflow as tf
mse = tf.keras.losses.MeanSquaredError()
y_true = tf.constant([3.0, -0.5, 2.0, 7.0])
y_pred = tf.constant([2.5, 0.0, 2.0, 8.0])
loss = mse(y_true, y_pred)
mae = tf.keras.losses.MeanAbsoluteError()
loss = mae(y_true, y_pred)
huber = tf.keras.losses.Huber(delta=1.0)
loss = huber(y_true, y_pred)
logcosh = tf.keras.losses.LogCosh()
loss = logcosh(y_true, y_pred)カスタム損失
カスタムの損失とは、(y_true, y_pred) を取り、スカラーのテンソルを返す任意の callable です。直列化やハイパーパラメータのためには、tf.keras.losses.Loss をサブクラス化し、call() + get_config() を実装しましょう。すべての演算を微分可能に保ちましょう。簡単な例を重み減衰し難しい例に集中させるのが、FocalLoss で — 物体検出で人気です。マスキングが機能してほしいなら、call() で Reduction.NONE を使い、最後に Keras に還元させましょう。
import tensorflow as tf
def weighted_mse(y_true, y_pred):
weights = tf.cast(y_true != 0, tf.float32)
return tf.reduce_sum(weights * tf.square(y_true - y_pred)) / tf.reduce_sum(weights)
class FocalLoss(tf.keras.losses.Loss):
def __init__(self, alpha=0.25, gamma=2.0, **kwargs):
super().__init__(**kwargs)
self.alpha = alpha
self.gamma = gamma
def call(self, y_true, y_pred):
bce = tf.keras.losses.binary_crossentropy(y_true, y_pred)
p = y_pred
pt = p * y_true + (1 - p) * (1 - y_true)
return self.alpha * tf.pow(1 - pt, self.gamma) * bce
def get_config(self):
config = super().get_config()
config.update({'alpha': self.alpha, 'gamma': self.gamma})
return config
loss = FocalLoss(alpha=0.25, gamma=2.0)Logits からの損失
softmax とクロスエントロピーを別々に計算すると、大きなロジット(e^100)でオーバーフローし得ます。from_logits=True を渡せば、TF が数値的に安定な log-sum-exp のトリックでそれらを融合します。同じことをするのが、tf.nn.*_cross_entropy_with_logits の関数型 API です。from_logits=True を使うときは、モデルが softmax/sigmoid で終わらないことを確保しましょう。さもなければ、活性化を二重に適用します。
import tensorflow as tf
# why logits? numerical stability
logits = tf.constant([[100.0, 0.0, 0.0]])
# BAD: softmax first then CCE (can overflow)
probs = tf.nn.softmax(logits)
loss_bad = tf.keras.losses.CategoricalCrossentropy()(
tf.constant([[1.0, 0.0, 0.0]]), probs)
# GOOD: from_logits=True uses log-sum-exp internally
loss_good = tf.keras.losses.CategoricalCrossentropy(from_logits=True)(
tf.constant([[1.0, 0.0, 0.0]]), logits)
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=z)
loss = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=z)マルチ出力の損失
マルチ出力のモデルのためには、出力名を損失関数へマッピングする dict と、バランスを取る loss_weights の dict を渡しましょう。総損失は重み付きの和です。マルチタスク学習の標準のパターンがこれです — 各ヘッドが自身の損失とメトリックを得ます。fit のとき、同じキーを持つ dict として訓練ターゲットを渡しましょう。どのタスクも勾配を支配しないよう、loss_weights を調整しましょう。
import tensorflow as tf
model.compile(
optimizer='adam',
loss={
'priority': tf.keras.losses.BinaryCrossentropy(from_logits=True),
'department': tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
},
loss_weights={'priority': 1.0, 'department': 0.5},
metrics={'priority': ['accuracy'], 'department': ['accuracy']},
)
inputs = tf.keras.Input(shape=(64,))
x = tf.keras.layers.Dense(64, activation='relu')(inputs)
out_a = tf.keras.layers.Dense(1, name='priority')(x)
out_b = tf.keras.layers.Dense(10, name='department')(x)
model = tf.keras.Model(inputs, [out_a, out_b])
model.fit(x_train, {'priority': y_pri, 'department': y_dep}, epochs=5)オプティマイザ
Adam
ほとんどのタスクでのデフォルトのオプティマイザであるのが、Adam です — パラメータごとの適応的な学習率を持ち、ハイパーパラメータの選択に頑健です。1 次と 2 次のモーメントの EMA 減衰を制御するのが、beta_1/beta_2 です。訓練をかけ LR を減衰させるには、float の代わりに LearningRateSchedule のオブジェクトを渡しましょう。結合ノルムが閾値を超えると全勾配を再スケールするのが、global_clipnorm で — RNN と transformers に重要です。
import tensorflow as tf
opt = tf.keras.optimizers.Adam(learning_rate=1e-3)
opt = tf.keras.optimizers.Adam(
learning_rate=1e-3, beta_1=0.9, beta_2=0.999,
epsilon=1e-7, amsgrad=False,
)
# schedule as learning_rate
lr_schedule = tf.keras.optimizers.schedules.CosineDecay(
initial_learning_rate=1e-3, decay_steps=10000)
opt = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
# gradient clipping
opt = tf.keras.optimizers.Adam(learning_rate=1e-3, global_clipnorm=1.0)SGD
大バッチの CNN 訓練では、SGD + momentum がしばしば Adam より良く汎化しますが、より多くの LR 調整を代償とします。標準が、momentum=0.9 で、Nesterov が小さな追加の利点を与えます。分離された L2 正則化を加えるのが、weight_decay です(Keras 3)— 古いバージョンでは、代わりに層上の kernel_regularizer を使います。SGD が箱から出して即座に Adam に対抗するには、ウォームアップと LR スケジューリングが必要です。
import tensorflow as tf
opt = tf.keras.optimizers.SGD(learning_rate=0.01)
opt = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)
opt = tf.keras.optimizers.SGD(
learning_rate=0.01, momentum=0.9, nesterov=True)
# with weight decay (Keras 2.13+ / 3.x)
opt = tf.keras.optimizers.SGD(
learning_rate=0.01, momentum=0.9, weight_decay=1e-4)
# clip gradients by value
opt = tf.keras.optimizers.SGD(
learning_rate=0.01, momentum=0.9, clipvalue=0.5)AdamW と他のオプティマイザ
重み減衰を勾配の更新から分離するのが、AdamW で、スケールで重要になります(transformers、大きい CNN)。RNN のクラシックなオプティマイザが、RMSprop です。パラメータごとに適応するが早く停滞し得るのが、Adagrad で — スパースな特徴には構いません。スパースな特徴を持つ大規模なオンライン学習のために設計されたのが、FTRL です(クリックスルー予測)。新しいプロジェクトでは、AdamW から始めましょう。
import tensorflow as tf
opt = tf.keras.optimizers.AdamW(
learning_rate=3e-4, weight_decay=0.01,
beta_1=0.9, beta_2=0.999)
opt = tf.keras.optimizers.RMSprop(learning_rate=1e-3, rho=0.9)
opt = tf.keras.optimizers.Adagrad(learning_rate=1e-2)
opt = tf.keras.optimizers.Adadelta(learning_rate=1.0)
opt = tf.keras.optimizers.Nadam(learning_rate=1e-3)
opt = tf.keras.optimizers.Ftrl(learning_rate=0.1)勾配の適用
カスタムの訓練ループでは、GradientTape で勾配を計算し、その後、opt.apply_gradients(zip(grads, vars)) を呼びます。カスタムの訓練ループの構成要素がこれです(カスタム訓練ループのセクションを参照)。結合 L2 ノルムが閾値の下に留まるよう勾配を再スケールするのが、clip_by_global_norm です。None の勾配は、変数が損失に影響しなかったことを意味します — 未使用のパラメータでよくあり、ログを取る価値があります。
import tensorflow as tf
opt = tf.keras.optimizers.Adam(1e-3)
vars = [w, b]
with tf.GradientTape() as tape:
preds = model(x)
loss = loss_fn(y, preds)
grads = tape.gradient(loss, vars)
grads, _ = tf.clip_by_global_norm(grads, 1.0)
opt.apply_gradients(zip(grads, vars))
for v, g in zip(vars, grads):
print(v.name, g is not None, g.numpy().norm() if g is not None else None)学習率スケジュール
LearningRateSchedule のオブジェクトは、オプティマイザのステップカウンタの関数として LR を計算します。alpha*initial_lr へ滑らかにアニールするのが、CosineDecay で — 強いデフォルトです。SGDR 風のウォームリスタートを実装するのが、CosineDecayRestarts です。オプティマイザの構築時に、learning_rate としてスケジュールを渡しましょう。Keras が各ステップで自動的に呼びます。ウォームアップのためには、カスタムのスケジュールで包むか、tensorflow/addons の WarmUp コールバックを使いましょう。
import tensorflow as tf
sched = tf.keras.optimizers.schedules.PiecewiseConstantDecay(
boundaries=[500, 1500], values=[1e-3, 1e-4, 1e-5])
sched = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-3, decay_steps=1000, decay_rate=0.96,
staircase=True)
sched = tf.keras.optimizers.schedules.CosineDecay(
initial_learning_rate=1e-3, decay_steps=10000, alpha=0.0)
opt = tf.keras.optimizers.Adam(learning_rate=sched)
print(opt.learning_rate(opt.iterations))勾配のクリッピングと EMA
(すべての勾配を一緒に再スケールする)global_clipnorm が最もよくある選択で、transformers が使うものです。各要素をハードクランプするのが、clipvalue です。カスタムのクリッピングのためには、tape.gradient と apply_gradients の間で勾配を修正しましょう。重みの指数移動平均(EMA)は、推論で小さな精度の向上をしばしば与えます — 各ステップの後で適用し、評価に平均化された重みを使いましょう。TF Addons には、MovingAverage のオプティマイザラッパーがあります。
import tensorflow as tf
opt = tf.keras.optimizers.Adam(1e-3, global_clipnorm=1.0)
opt = tf.keras.optimizers.Adam(1e-3, clipvalue=0.5)
opt = tf.keras.optimizers.Adam(1e-3, clipnorm=1.0)
# manual clipping (more control)
grads = tape.gradient(loss, vars)
grads = [tf.clip_by_norm(g, 1.0) if g is not None else g for g in grads]
grads, _ = tf.clip_by_global_norm(grads, 1.0)
opt.apply_gradients(zip(grads, vars))
# exponential moving average of weights (improves generalization)
ema = tf.train.ExponentialMovingAverage(decay=0.999)訓練
compile と fit
fit は高レベルの 訓練 API です:バッチ化、シャッフル、検証、コールバック、進捗を扱います。validation_data=(x, y) か validation_split=0.2(訓練から外れます)のどちらかを渡しましょう。1 エポックごとに 1 行表示するのが、verbose=2 で(ログに良く)、進捗バーを表示するのが 1 です。返される history オブジェクトが、エポックごとの損失とメトリックを保存します — 過学習を見つけるためにプロットしましょう。
import tensorflow as tf
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
history = model.fit(
x_train, y_train, batch_size=32, epochs=10,
validation_data=(x_val, y_val),
validation_split=0.2, shuffle=True, verbose=2,
)
print(history.history['loss'])検証とメトリック
メトリックは、バッチをまたいで蓄積し、エポック終了時に最終値を計算するステートフルなオブジェクトです — 損失と違い、訓練に影響しません。文字列(「accuracy」)かカスタムメトリックのための Metric オブジェクトを渡しましょう。tf.keras.metrics.Metric をサブクラス化し、update_state/result/reset_state を実装します。各エポックの開始時に呼ばれるのが、reset_state です(TF 2.11+ で reset_states から改名されました)。
model.compile(
optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=[
'accuracy',
tf.keras.metrics.SparseTopKCategoricalAccuracy(k=5, name='top5_acc'),
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall'),
],
)
class F1Score(tf.keras.metrics.Metric):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.precision = tf.keras.metrics.Precision()
self.recall = tf.keras.metrics.Recall()
def update_state(self, y_true, y_pred, sample_weight=None):
self.precision.update_state(y_true, y_pred, sample_weight)
self.recall.update_state(y_true, y_pred, sample_weight)
def result(self):
p, r = self.precision.result(), self.recall.result()
return 2 * p * r / (p + r + 1e-8)
def reset_state(self):
self.precision.reset_state(); self.recall.reset_state()エポック、バッチサイズ、ステップ
tf.data.Dataset を使うときは、batch_size を渡してはいけません — データセットは既にバッチ化されています。データセットが無限に繰り返すとき、1 エポックを構成するバッチ数を fit に伝えるのが、steps_per_epoch です。検証で同じことをするのが、validation_steps です。チェックポイントから訓練を再開するには、initial_epoch を使いましょう — fit は最初の N エポックをスキップしますが、オプティマイザの状態(LR スケジュール、momentum)は正しく続きます。
model.fit(x_train, y_train, batch_size=32, epochs=10)
# with tf.data.Dataset
model.fit(train_dataset, epochs=10, validation_data=val_dataset)
# Dataset of unknown size: use steps_per_epoch
model.fit(
train_dataset, epochs=10, steps_per_epoch=500,
validation_data=val_dataset, validation_steps=50,
)
# initial epoch (resume training)
model.fit(train_dataset, initial_epoch=5, epochs=10)クラスとサンプルの重み
不均衡に対抗するため各クラスの損失をスケールするのが、class_weight で — 余分な計算なしのオーバーサンプリングに相当します。例ごとの制御を与えるのが、sample_weight で、難しい例のマイニングやパディング位置のマスキングに有用です。tf.data.Dataset を使うときは、データセットが (x, y, w) を出すよう、3 番目のタプル要素として sample_weight を含めましょう。バランスの取れた重みを自動的に計算するのが、sklearn.utils.class_weight です。
class_weight = {0: 1.0, 1: 5.0, 2: 1.0} # class 1 is rare
model.fit(x_train, y_train, class_weight=class_weight, epochs=10)
sample_weight = np.where(y_train == 1, 5.0, 1.0)
model.fit(x_train, y_train, sample_weight=sample_weight, epochs=10)
# with Dataset: yield (x, y, sample_weight) tuples
ds = tf.data.Dataset.from_tensor_slices((x, y, w))
model.fit(ds, epochs=10)
from sklearn.utils import class_weight
cw = class_weight.compute_class_weight('balanced', classes=np.unique(y), y=y)
class_weight = dict(enumerate(cw))Predict と Evaluate
全入力の予測の NumPy 配列を返すのが、predict です — メモリを制御するには batch_size を使いましょう。compile からの損失と任意のメトリックを返すのが、evaluate です。非常に大きい入力のためには、predict_on_batch でバッチを手動で反復しましょう。モデルを直接呼ぶ(model(x))と、テンソルが返り training= が尊重されますが、predict は常に推論モードで走り NumPy を返します。テスト時の拡張には、model(x, training=True) を使いましょう。