Keras Frameworkは、人工知能・機械学習分野における重要な概念・技術です。
Keras は、Python で深層学習モデルを簡潔に記述できる高レベル API です。2015 年に François Chollet(Google)によって作成され、初心者にも使いやすいシンプルなインターフェースと、プロダクション対応の柔軟性を兼ね備えています。2017 年以降 TensorFlow の公式 API となり、2023 年にリリースされた Keras 3 では TensorFlow、PyTorch、JAX のいずれもバックエンドとして選択可能になりました。
tf.keras と keras の両方で使用可能from keras import layers, models
model = models.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.2),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
より柔軟な構造を記述可能:
from keras import Input, Model
inputs = Input(shape=(784,))
x = layers.Dense(128, activation='relu')(inputs)
x = layers.Dropout(0.2)(x)
x = layers.Dense(64, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)
model = Model(inputs, outputs)
# 学習
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
# 評価
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.3f}")
# 予測
predictions = model.predict(x_test)
# 保存
model.save('my_model.keras')
# 読込
loaded_model = keras.models.load_model('my_model.keras')
最も基本的な層。すべての入力と出力が接続。
import os
os.environ["KERAS_BACKEND"] = "torch" # "tensorflow", "torch", "jax"
import keras
# 同じ Keras API がバックエンドに応じて動作
コンピュータビジョン専用ライブラリ:
自然言語処理専用ライブラリ:
ハイパーパラメータ自動最適化:
| 項目 | Keras | TensorFlow(低レベル) | PyTorch |
|---|---|---|---|
| 学習曲線 | 緩やか | 急 | 中 |
| コード量 | 少 | 多 | 中 |
| 柔軟性 | 中 | 高 | 高 |
| デバッグ | 容易 | やや難 | 容易 |
| 本番デプロイ | TF Lite、TF Serving | 最適 | TorchScript、ONNX |
| 研究用途 | 限定的 | 強力 | 最強 |
| 企業利用 | 広範 | Google 主導 | Meta 主導 |
# 仮想環境作成
python -m venv keras_env
source keras_env/bin/activate # Linux/Mac
# keras_env\Scripts\activate # Windows
# Keras + バックエンド
pip install keras tensorflow # TensorFlow バックエンド
pip install keras torch # PyTorch バックエンド
pip install keras jax[cuda12] # JAX バックエンド(GPU)
# NVIDIA GPU(CUDA 必須)
pip install tensorflow[and-cuda] # TensorFlow
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 # PyTorch
| 用途 | GPU | VRAM |
|---|---|---|
| 学習入門 | RTX 4060 | 8GB |
| 実務レベル | RTX 4070 Ti | 16GB |
| 大規模モデル | RTX 4090 | 24GB |
| 研究用途 | A100 / H100 | 40-80GB |