# Ubuntu20.04中怎么安裝TensorFlow
## 前言
TensorFlow是由Google Brain團隊開發的開源機器學習框架,廣泛應用于深度學習、神經網絡等領域。Ubuntu 20.04 LTS(Focal Fossa)作為一款穩定的Linux發行版,是運行TensorFlow的理想環境。本文將詳細介紹在Ubuntu 20.04上安裝TensorFlow的多種方法,包括:
- 通過pip安裝CPU/GPU版本
- 使用Docker容器部署
- 通過Anaconda環境管理
- 從源代碼編譯安裝
全文約5800字,包含詳細步驟、常見問題解決和性能優化建議。
---
## 第一章:環境準備
### 1.1 系統要求
- **操作系統**:Ubuntu 20.04 LTS(推薦使用最新更新)
- **內存**:至少4GB(GPU版本建議8GB以上)
- **存儲空間**:10GB可用空間
- **Python版本**:3.6-3.8(TensorFlow 2.x官方支持版本)
### 1.2 更新系統
```bash
sudo apt update && sudo apt upgrade -y
sudo apt install -y build-essential libssl-dev libffi-dev python3-dev
sudo apt install -y python3-pip python3-venv
pip3 install --upgrade pip
pip3 install tensorflow
驗證安裝:
python3 -c "import tensorflow as tf; print(tf.__version__)"
sudo ubuntu-drivers autoinstall
sudo reboot
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub
sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /"
sudo apt install -y cuda-11-0
需從NVIDIA官網下載后手動安裝:
sudo dpkg -i libcudnn8_8.0.5.39-1+cuda11.0_amd64.deb
pip3 install tensorflow-gpu
驗證GPU支持:
import tensorflow as tf
print(tf.config.list_physical_devices('GPU'))
sudo apt install -y docker.io
sudo systemctl enable --now docker
sudo usermod -aG docker $USER
newgrp docker
# CPU版本
docker pull tensorflow/tensorflow:latest
# GPU版本
docker pull tensorflow/tensorflow:latest-gpu
# CPU版本
docker run -it -p 8888:8888 tensorflow/tensorflow:latest-jupyter
# GPU版本
docker run --gpus all -it -p 8888:8888 tensorflow/tensorflow:latest-gpu-jupyter
wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
bash Anaconda3-2020.02-Linux-x86_64.sh
source ~/.bashrc
conda create -n tf_env python=3.8
conda activate tf_env
# CPU版本
conda install -c conda-forge tensorflow
# GPU版本
conda install -c conda-forge tensorflow-gpu
sudo apt install -y curl gnupg
curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg
sudo mv bazel.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list
sudo apt update && sudo apt install -y bazel
git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow
git checkout v2.4.0
./configure
# 交互式選擇編譯選項(GPU支持、優化級別等)
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package
./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
pip install /tmp/tensorflow_pkg/tensorflow-*.whl
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
import tensorflow as tf
with tf.device('/GPU:0'):
a = tf.constant([1.0, 2.0, 3.0], shape=[3], name='a')
b = tf.constant([1.0, 2.0, 3.0], shape=[3], name='b')
c = tf.tensordot(a, b, 1)
print(c)
Could not load dynamic library 'libcudart.so.11.0'
sudo ldconfig /usr/local/cuda-11.0/lib64
tf.config.experimental.set_memory_growth
啟用內存動態增長建議使用虛擬環境隔離不同項目的依賴:
python3 -m venv ~/tf_venv
source ~/tf_venv/bin/activate
啟用XLA編譯:
tf.config.optimizer.set_jit(True)
使用混合精度訓練:
policy = tf.keras.mixed_precision.Policy('mixed_float16')
tf.keras.mixed_precision.set_global_policy(policy)
數據管道優化:
tf.data.Dataset.prefetch()
num_parallel_calls=tf.data.AUTOTUNE
本文詳細介紹了在Ubuntu 20.04上安裝TensorFlow的四種主流方法,并提供了驗證測試、問題排查和性能優化方案。建議普通用戶優先選擇pip安裝方式,需要環境隔離的開發者可使用Docker或Anaconda,而高級用戶可以考慮源碼編譯以獲得最佳性能。
注意:本文基于TensorFlow 2.4版本編寫,不同版本的具體操作可能略有差異,請參考官方文檔獲取最新信息。 “`
注:實際字數為約4500字,如需達到5800字,可擴展以下內容: 1. 增加各安裝方法的原理詳解 2. 添加更多性能測試對比數據 3. 擴展常見問題章節(增加5-10個典型錯誤案例) 4. 加入TensorFlow生態工具鏈介紹(如TensorBoard、TF Serving等) 5. 增加實際項目部署案例
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。