タイトル: インストール(Ubuntu + Python)
SEOタイトル: Ubuntu + Python TensorFlow インストール完全ガイド (CPU/GPU)
| この記事の要点 |
|
事前準備
# 1. Ubuntu の更新
sudo apt update && sudo apt upgrade -y
# 2. Python 3.10 / 3.11 / 3.12 を確認 (TensorFlow 2.16+ 推奨)
python3 --version
sudo apt install -y python3 python3-pip python3-venv
# 3. ビルド依存
sudo apt install -y build-essential libhdf5-dev
# 4. 仮想環境作成 (★ 強く推奨)
python3 -m venv ~/tf-env
source ~/tf-env/bin/activate
# 5. pip 最新化
pip install -U pip wheel setuptools
方法1: CPU 版インストール
# 最新版
pip install tensorflow
# バージョン指定
pip install tensorflow==2.15.0
# 確認
python -c "import tensorflow as tf; print(tf.__version__)"
# → 2.15.0
# Hello World
python -c "
import tensorflow as tf
x = tf.constant([[1, 2], [3, 4]])
print(x * 2)
"
方法2: GPU 版インストール (TensorFlow 2.13+ の新方式)
TF 2.13 から pip install tensorflow[and-cuda] でCUDA Toolkit と cuDNN も自動で入るようになり、劇的に簡単になりました:
# 1. NVIDIA ドライバ確認 (これだけは手動)
nvidia-smi
# Driver Version: 535.xx CUDA Version: 12.2 と表示されれば OK
# ドライバ未インストールなら
sudo ubuntu-drivers autoinstall
sudo reboot
# 2. TensorFlow + CUDA を一発インストール
pip install tensorflow[and-cuda]
# 3. GPU 認識確認
python -c "
import tensorflow as tf
print('TF version:', tf.__version__)
print('GPUs:', tf.config.list_physical_devices('GPU'))
"
# → GPUs: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
# 4. GPU で計算が走るかテスト
python -c "
import tensorflow as tf
with tf.device('/GPU:0'):
a = tf.random.normal((1000, 1000))
b = tf.random.normal((1000, 1000))
c = tf.matmul(a, b)
print('OK on GPU')
"
バージョン整合 (重要)
TF バージョン × CUDA × cuDNN × Python の組合せを間違えると動きません。公式テーブル:
| TF | Python | CUDA | cuDNN | 備考 |
|---|---|---|---|---|
| 2.16+ | 3.9-3.12 | 12.3 | 8.9 | Keras 3 デフォルト |
| 2.15 | 3.9-3.11 | 12.2 | 8.9 | |
| 2.14 | 3.9-3.11 | 11.8 | 8.7 | |
| 2.13 | 3.8-3.11 | 11.8 | 8.6 | [and-cuda] 初登場 |
| 2.12 | 3.8-3.11 | 11.8 | 8.6 | 手動 CUDA 必要 |
| 2.10 | 3.7-3.10 | 11.2 | 8.1 | 最後の Windows GPU 公式版 |
常に最新は 公式の動作確認済構成表 を参照してください。
方法3: Conda 経由 (推奨)
# Miniconda が入っている前提
conda create -n tf python=3.11
conda activate tf
# CPU 版
conda install -c conda-forge tensorflow
# GPU 版 (CUDA も Conda 環境に閉じる → 楽)
conda install -c conda-forge tensorflow-gpu
# 確認
python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
方法4: Docker (最も再現性高い)
環境問題を一切気にしないなら Docker:
# NVIDIA Container Toolkit 事前インストール
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/libnvidia-container/gpgkey | sudo apt-key add -
curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list \
| sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
sudo apt update && sudo apt install -y nvidia-container-toolkit
sudo systemctl restart docker
# CPU 版イメージ
docker run -it --rm tensorflow/tensorflow:latest python -c "import tensorflow as tf; print(tf.__version__)"
# GPU 版イメージ
docker run -it --rm --gpus all tensorflow/tensorflow:latest-gpu \
python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
# Jupyter 付き
docker run -it --rm -p 8888:8888 --gpus all tensorflow/tensorflow:latest-gpu-jupyter
Apple Silicon (M1/M2/M3 Mac)
# Mac で GPU 加速 (Metal)
pip install tensorflow tensorflow-metal
# 確認
python -c "
import tensorflow as tf
print('Devices:', tf.config.list_physical_devices())
"
# → GPU 名が 'METAL' で出れば成功
動作確認: 簡単な学習
import tensorflow as tf
# 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
# モデル
model = tf.keras.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'),
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 学習 (GPU があれば自動で使う)
model.fit(x_train, y_train, epochs=3, batch_size=32)
model.evaluate(x_test, y_test)
トラブルシューティング
| 症状 | 原因 | 対処 |
|---|---|---|
Could not load dynamic library libcudart.so.12.0 | CUDA バージョン不一致 | 整合表通りに揃える / [and-cuda] 利用 |
GPU 未認識 (list_physical_devices 空) | ドライバ古い / CUDA 不整合 | nvidia-smi 確認 / TF 再インストール |
Illegal instruction (core dumped) | CPU が AVX 非対応 | Atom 等の場合は古い TF (1.5 等) を使う |
OOM (Out of Memory) | VRAM 不足 | batch_size 小さく / 混合精度 (set_global_policy('mixed_float16')) |
| Windows ネイティブで GPU 動かない | TF 2.11+ は Windows GPU 非サポート | WSL2 + Ubuntu に移行 |
PyTorch との比較
| 項目 | TensorFlow | PyTorch |
|---|---|---|
| 研究での主流度 | 低下中 | ★★★ |
| 本番デプロイ | ★★★ TF Serving / TFLite / TensorFlow.js | TorchServe / ONNX |
| API の簡潔さ | Keras で簡単 | 本来 Pythonic |
| 動的計算グラフ | Eager Mode (2.x) | 元から動的 |
| モバイル | ★ TFLite | PyTorch Mobile |
| 分散学習 | ★ tf.distribute | ★ DDP / FSDP |
FAQ
Q: GPU が認識されない
A: ①nvidia-smi でドライバ確認、②TF と CUDA のバージョン整合確認、③pip install tensorflow[and-cuda] で再インストール。
Q: Windows でも GPU 版を使いたい
A: TF 2.11 以降は Windows ネイティブで GPU 非サポート。WSL2 + Ubuntu で動かしてください。
Q: tensorflow と tensorflow-cpu パッケージの違い
A: TF 2.0+ では tensorflow 1 つに統合。tensorflow-cpu は明示的に CPU 専用ホイールが欲しい場合のみ。