TensorFlow 高級 API - Keras
Keras は Python で書かれた高級ニューラルネットワーク API であり、TensorFlow、CNTK、または Theano をバックエンドとして実行できます。Keras の設計理念は、ユーザーフレンドリー、モジュール化、拡張の容易さです。
Keras の主な特徴
- シンプルで使いやすい:直感的で一貫性のあるインターフェースを提供し、迅速なプロトタイプ設計に適しています
- モジュール化:ニューラルネットワーク層、損失関数、オプティマイザなどはすべてプラグイン可能なモジュールです
- 拡張が容易:新しいモジュールを簡単に追加して、新しい研究アイデアを表現できます
- マルチバックエンド対応:TensorFlow、CNTK、または Theano 上でシームレスに実行できます
Keras の核心概念
1. モデル (Model)
Keras の核心的なデータ構造はモデルであり、モデルはニューラルネットワークの層を編成する方法です。Keras は2つの主要なモデルを提供します:
- Sequential モデル:層の線形な積み重ね
- Functional API:複雑なモデルを構築するための有向非巡回グラフ
2. レイヤー (Layer)
レイヤーは Keras の基本的な構成要素であり、各レイヤーは入力データを受け取り、何らかの計算を行った後に結果を出力します。Keras はさまざまな定義済みレイヤーを提供します:
- コアレイヤー:Dense、Activation、Dropout など
- 畳み込みレイヤー:Conv2D、MaxPooling2D など
- リカレントレイヤー:LSTM、GRU など
- その他:Embedding、BatchNormalization など
3. 活性化関数 (Activation Function)
活性化関数はニューロンの出力を決定し、よく使われるものには次のものがあります:
- ReLU (Rectified Linear Unit)
- Sigmoid
- Tanh
- Softmax(多クラス分類問題)
Keras の基本的なワークフロー
1. モデルの定義
例
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(784,)),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(784,)),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
2. モデルのコンパイル
例
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
loss='categorical_crossentropy',
metrics=['accuracy'])
3. モデルのトレーニング
例
model.fit(x_train, y_train,
epochs=5,
batch_size=32)
epochs=5,
batch_size=32)
4. モデルの評価
例
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
5. 予測の実行
例
classes = model.predict(x_test, batch_size=128)
Keras のよく使うレイヤーの詳細
1. Dense 全結合層
例
Dense(units,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros')
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros')
units:正の整数、出力空間の次元activation:活性化関数use_bias:バイアスベクトルを使用するかどうかkernel_initializer:重み行列の初期化子bias_initializer:バイアスベクトルの初期化子
2. Conv2D 2次元畳み込み層
例
Conv2D(filters,
kernel_size,
strides=(1, 1),
padding='valid',
activation=None)
kernel_size,
strides=(1, 1),
padding='valid',
activation=None)
filters:畳み込みカーネルの数kernel_size:畳み込みカーネルのサイズstrides:畳み込みのストライドpadding:パディング方式('valid' または 'same')
3. LSTM 長短期記憶ネットワーク層
例
LSTM(units,
activation='tanh',
recurrent_activation='hard_sigmoid',
return_sequences=False)
activation='tanh',
recurrent_activation='hard_sigmoid',
return_sequences=False)
units:正の整数、出力空間の次元activation:活性化関数recurrent_activation:リカレントステップの活性化関数return_sequences:完全なシーケンスを返すかどうか
Keras モデルの保存と読み込み
1. モデル全体の保存
例
model.save('my_model.h5') # アーキテクチャ、重み、トレーニング設定を保存
2. アーキテクチャのみの保存
例
json_string = model.to_json() # JSONとして保存
yaml_string = model.to_yaml() # YAMLとして保存
yaml_string = model.to_yaml() # YAMLとして保存
3. 重みのみの保存
例
model.save_weights('my_model_weights.h5')
4. モデルの読み込み
例
from tensorflow.keras.models import load_model
model = load_model('my_model.h5') # 完全なモデルを読み込み
model = load_model('my_model.h5') # 完全なモデルを読み込み
Keras コールバック関数
コールバック関数は、トレーニングプロセスの特定の時点で呼び出される関数であり、次の目的で使用されます:
- モデルのチェックポイント
- 早期停止
- 学習率の調整
- ログ記録など
よく使うコールバック関数
例
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
callbacks = [
ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True),
EarlyStopping(monitor='val_loss', patience=3)
]
model.fit(x_train, y_train,
epochs=10,
callbacks=callbacks,
validation_data=(x_val, y_val))
callbacks = [
ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True),
EarlyStopping(monitor='val_loss', patience=3)
]
model.fit(x_train, y_train,
epochs=10,
callbacks=callbacks,
validation_data=(x_val, y_val))
Keras 実践例:MNIST 手書き数字認識
例
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
# データの読み込み
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# データの前処理
x_train = x_train.reshape(60000, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(10000, 28, 28, 1).astype('float32') / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# モデルの構築
model = Sequential([
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.25),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
# モデルのコンパイル
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# モデルのトレーニング
model.fit(x_train, y_train,
batch_size=128,
epochs=12,
verbose=1,
validation_data=(x_test, y_test))
# モデルの評価
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
# データの読み込み
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# データの前処理
x_train = x_train.reshape(60000, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(10000, 28, 28, 1).astype('float32') / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# モデルの構築
model = Sequential([
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.25),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
# モデルのコンパイル
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# モデルのトレーニング
model.fit(x_train, y_train,
batch_size=128,
epochs=12,
verbose=1,
validation_data=(x_test, y_test))
# モデルの評価
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Keras 上級テクニック
1. カスタムレイヤー
例
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape)
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
from tensorflow.keras.layers import Layer
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape)
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
2. カスタム損失関数
例
from tensorflow.keras import backend as K
def custom_loss(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
model.compile(optimizer='adam', loss=custom_loss)
def custom_loss(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
model.compile(optimizer='adam', loss=custom_loss)
3. 学習率スケジューリング
例
from tensorflow.keras.callbacks import LearningRateScheduler
def scheduler(epoch, lr):
if epoch < 10:
return lr
else:
return lr * K.exp(-0.1)
callback = LearningRateScheduler(scheduler)
model.fit(x_train, y_train, epochs=15, callbacks=[callback])
def scheduler(epoch, lr):
if epoch < 10:
return lr
else:
return lr * K.exp(-0.1)
callback = LearningRateScheduler(scheduler)
model.fit(x_train, y_train, epochs=15, callbacks=[callback])
Keras よくある問題と解決策
1. 過学習の問題
- Dropout レイヤーを追加する
- L1/L2 正則化を使用する
- トレーニングデータを増やす
- データ拡張を使用する
2. トレーニング速度が遅い
- バッチサイズを大きくする
- よりシンプルなモデルを使用する
- 異なるオプティマイザを試す
- GPU アクセラレーションを使用する
3. 勾配消失・爆発
- BatchNormalization を使用する
- 適切な重みの初期化を使用する
- ReLU などの非飽和活性化関数を使用する
- 勾配クリッピングを使用する
まとめ
Keras は TensorFlow の高級 API として、ディープラーニングモデルを構築・トレーニングするためのシンプルで直感的なインターフェースを提供します。この記事を通じて、あなたは以下を習得したはずです:
- Keras の核心概念と基本的なワークフロー
- よく使うレイヤーの使用方法
- モデルの保存と読み込み
- コールバック関数の使用方法
- 実際のプロジェクトでの応用例
- 上級テクニックとよくある問題の解決策
Keras の強力さは、その柔軟性と使いやすさにあり、ディープラーニングモデルの開発をより効率的にします。実践を重ねるにつれて、さまざまな実際の問題を解決するために、より複雑なニューラルネットワークモデルを構築できるようになるでしょう。
その他の拡張