Skip to content

第 14 章 ソースコード一覧

書籍第 14 章「深層学習の基礎と生成AIの活用」に掲載しているソースコードの一覧です。番号は書籍の「入力」番号と対応しています。上のバッジから、この章のコードをまとめた Google Colab ノートブックを開けます。

入力 14.1: TensorFlowのインストール

# Google Colabでは不要(プリインストール済み)
# ローカル環境の場合は、以下の # を外してインストールコマンドを実行してください
# !pip install tensorflow

入力 14.2: TensorFlowのバージョン確認

import tensorflow as tf
print(tf.__version__)

入力 14.3: MNISTデータの読み込みと前処理

from tensorflow.keras.datasets import mnist

# データの読み込み(MNISTは第11章でも使用)
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 画素値を0〜1に正規化
X_train = X_train / 255.0
X_test = X_test / 255.0

# 28×28の画像を784次元のベクトルに変換(Flatten)
X_train_flat = X_train.reshape(-1, 784)
X_test_flat = X_test.reshape(-1, 784)

print(f"変換後の訓練データ: {X_train_flat.shape}")

入力 14.4: 全結合ニューラルネットワークの構築

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input

# モデルの構築
model = Sequential([
    Input(shape=(784,)),              # 入力の形状を指定
    Dense(128, activation="relu"),    # 隠れ層1
    Dense(64, activation="relu"),     # 隠れ層2
    Dense(10, activation="softmax")   # 出力層(10クラス)
])

# モデルの概要を表示
model.summary()

入力 14.5: モデルのコンパイルと学習

# モデルのコンパイル
model.compile(
    optimizer="adam",                        # オプティマイザ
    loss="sparse_categorical_crossentropy",  # 損失関数
    metrics=["accuracy"]                     # 評価指標
)

# モデルの学習
history = model.fit(
    X_train_flat, y_train,
    epochs=10,           # 学習を10回繰り返す
    batch_size=32,       # 32サンプルずつまとめて計算
    validation_split=0.2 # 訓練データの20%を検証用に使用
)

入力 14.6: テストデータによるモデルの評価

# テストデータで評価
test_loss, test_accuracy = model.evaluate(X_test_flat, y_test)
print(f"テスト精度: {test_accuracy:.4f}")

入力 14.7: 学習曲線の描画

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(12, 4))

# 精度の推移
axes[0].plot(history.history["accuracy"], label="訓練")
axes[0].plot(history.history["val_accuracy"], label="検証")
axes[0].set_title("精度の推移")
axes[0].set_xlabel("エポック")
axes[0].set_ylabel("精度")
axes[0].legend()

# 損失の推移
axes[1].plot(history.history["loss"], label="訓練")
axes[1].plot(history.history["val_loss"], label="検証")
axes[1].set_title("損失の推移")
axes[1].set_xlabel("エポック")
axes[1].set_ylabel("損失")
axes[1].legend()

plt.tight_layout()
plt.show()

入力 14.8: CNN入力形状へのデータ変換

from tensorflow.keras.datasets import mnist

# データの再読み込みと前処理
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train / 255.0
X_test = X_test / 255.0

# CNNの入力形状に変換: (サンプル数, 高さ, 幅, チャンネル数)
X_train_cnn = X_train.reshape(-1, 28, 28, 1)
X_test_cnn = X_test.reshape(-1, 28, 28, 1)

print(f"CNN入力の形状: {X_train_cnn.shape}")

入力 14.9: CNNモデルの構築

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (
    Input, Conv2D, MaxPooling2D, Flatten, Dense
)

# CNNモデルの構築
cnn_model = Sequential([
    Input(shape=(28, 28, 1)),
    Conv2D(32, (3, 3), activation="relu"),
    MaxPooling2D((2, 2)),
    Conv2D(64, (3, 3), activation="relu"),
    MaxPooling2D((2, 2)),
    Flatten(),
    Dense(64, activation="relu"),
    Dense(10, activation="softmax")
])

cnn_model.summary()

入力 14.10: CNNモデルのコンパイルと学習

# コンパイルと学習
cnn_model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

cnn_history = cnn_model.fit(
    X_train_cnn, y_train,
    epochs=5,
    batch_size=64,
    validation_split=0.2
)

入力 14.11: CNNモデルの評価

# テストデータで評価
test_loss, test_accuracy = cnn_model.evaluate(X_test_cnn, y_test)
print(f"CNNのテスト精度: {test_accuracy:.4f}")

入力 14.12: CIFAR-10データの読み込み

from tensorflow.keras.datasets import cifar10

# データの読み込み(初回はダウンロードに時間がかかる)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

print(f"訓練データ: {X_train.shape}, ラベル: {y_train.shape}")
print(f"テストデータ: {X_test.shape}, ラベル: {y_test.shape}")

入力 14.13: CIFAR-10用CNNの構築と学習

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (
    Input, Conv2D, MaxPooling2D, Flatten, Dense
)

# 画素値を0〜1に正規化
X_train = X_train / 255.0
X_test = X_test / 255.0

# MNISTのCNNと同じ構造(入力形状のみ変更)
cifar_model = Sequential([
    Input(shape=(32, 32, 3)),
    Conv2D(32, (3, 3), activation="relu"),
    MaxPooling2D((2, 2)),
    Conv2D(64, (3, 3), activation="relu"),
    MaxPooling2D((2, 2)),
    Flatten(),
    Dense(64, activation="relu"),
    Dense(10, activation="softmax")
])

cifar_model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

cifar_history = cifar_model.fit(
    X_train, y_train,
    epochs=10,
    batch_size=64,
    validation_split=0.2
)

入力 14.14: CIFAR-10モデルの評価

# テストデータで評価
test_loss, test_accuracy = cifar_model.evaluate(X_test, y_test)
print(f"CIFAR-10のテスト精度: {test_accuracy:.4f}")

入力 14.15: transformersのインストール

# Google Colabでは不要(プリインストール済み)
# ローカル環境の場合は、以下の # を外してインストールコマンドを実行してください
# !pip install transformers

入力 14.16: パイプラインによる感情分析

from transformers import pipeline

# 感情分析パイプラインの作成
classifier = pipeline("sentiment-analysis")

# 英語テキストの感情分析
texts = [
    "I love this movie! It was absolutely wonderful.",
    "This product is terrible. I want a refund.",
    "The weather is okay today."
]
results = classifier(texts)

for text, result in zip(texts, results):
    print(f"{text}: {result['label']} ({result['score']:.4f})")

入力 14.17: 日本語テキストの感情分析

from transformers import pipeline

# 日本語感情分析モデルの利用
classifier_ja = pipeline(
    "sentiment-analysis",
    model="lxyuan/distilbert-base-multilingual-cased-sentiments-student"
)

# 日本語テキストの感情分析
texts_ja = [
    "この映画は最高でした!感動しました。",
    "サービスが悪くて非常に不満です。",
    "今日のランチは普通でした。"
]

results_ja = classifier_ja(texts_ja)

for text, result in zip(texts_ja, results_ja):
    print(f"{text}")
    print(f"  → {result['label']} ({result['score']:.4f})")
    print()

入力 14.18: ゼロショット分類の実行

from transformers import pipeline

# ゼロショット分類
zero_shot = pipeline(
    "zero-shot-classification",
    model="facebook/bart-large-mnli"
)

text = "Apple announced a new iPhone model with improved camera."
candidate_labels = ["technology", "sports", "politics", "entertainment"]

result = zero_shot(text, candidate_labels)

for label, score in zip(result["labels"], result["scores"]):
    print(f"  {label}: {score:.4f}")

入力 14.19: openaiライブラリのインストール

# Google Colabでは不要(プリインストール済み)
# ローカル環境の場合は、以下の # を外してインストールコマンドを実行してください
# !pip install openai

入力 14.20: OpenAI APIによるテキスト生成

from openai import OpenAI
import getpass
import os

# APIキーを画面に表示せず入力し、環境変数に設定
if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API key: ")

# 環境変数 OPENAI_API_KEY を自動的に読み込む
client = OpenAI()

# テキスト生成
response = client.responses.create(
    model="gpt-5-mini",
    instructions="あなたは親切なアシスタントです。",
    input="機械学習とは何かを3行で説明してください。"
)

print(response.output_text)

入力 14.21: プロンプトの書き方による出力の比較

# 曖昧なプロンプト
response1 = client.responses.create(
    model="gpt-5-mini",
    input="リスト内包表記について教えてください。"
)
print("【曖昧なプロンプト】")
print(response1.output_text[:200])
print("...")

# 具体的なプロンプト
response2 = client.responses.create(
    model="gpt-5-mini",
    instructions="あなたはプログラミング講師です。初心者向けに説明してください。",
    input="Pythonのリスト内包表記について、具体例を1つ含めて"
          "3行以内で説明してください。"
)
print("\n【具体的なプロンプト】")
print(response2.output_text)