okpy

Pythonエンジニア兼テックリーダーが、多くのプロジェクトとチーム運営から得た実践的な知識を共有するブログです。

Python TensorFlow ライブラリ完全ガイド

Python TensorFlow ライブラリ完全ガイド

TensorFlow は、Google によって開発されたオープンソース機械学習ライブラリで、ディープラーニング(深層学習)をはじめとする多様な数値計算に対応しています。本記事では、Python を用いて TensorFlow の基本的な使い方をコピー可能なコード付きで解説します。

1. TensorFlow の概要

インストール方法

pip install tensorflow

2. 主な機能と使用例

(1) ライブラリのインポートとバージョン確認

import tensorflow as tf
print(tf.__version__)

(2) データセットの読み込み(MNIST)

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

(3) モデルの構築(シーケンシャルモデル)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

(4) モデルのコンパイルと学習

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)

(5) モデルの評価

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print("Test accuracy:", test_acc)

(6) モデルの保存と読み込み

model.save('mnist_model')
new_model = tf.keras.models.load_model('mnist_model')

(7) カスタム層の作成

class MyLayer(tf.keras.layers.Layer):
    def __init__(self):
        super().__init__()
    def call(self, inputs):
        return tf.math.square(inputs)

(8) TensorBoard による可視化

import datetime
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

model.fit(x_train, y_train, epochs=5, callbacks=[tensorboard_callback])

(9) コールバックで学習を制御(EarlyStopping)

es_cb = tf.keras.callbacks.EarlyStopping(patience=2, restore_best_weights=True)
model.fit(x_train, y_train, epochs=10, validation_split=0.2, callbacks=[es_cb])

(10) 推論(予測)

predictions = model.predict(x_test)
print(tf.argmax(predictions[0]).numpy())

3. TensorFlow の主な機能まとめ

機能 説明
Keras API モデル構築・学習を簡潔に記述できる高水準 API
GPU 対応 大規模モデルや高速学習に最適化
callbacks 学習制御(EarlyStopping、ModelCheckpoint など)
TensorBoard ログ可視化、グラフ表示、学習履歴トラッキング
モデル保存・読込 .save() / load_model() によるシリアライズ

まとめ

TensorFlow は本格的な機械学習・深層学習モデルを Python で構築するための強力なライブラリです。直感的な記述でありながら高度なカスタマイズも可能で、研究開発から実運用まで幅広く活用できます。