wsl ubuntu安装tensorflow gpu
时间: 2025-06-21 15:36:08 浏览: 6
### 在WSL Ubuntu中安装支持GPU的TensorFlow
要在WSL (Windows Subsystem for Linux) 的Ubuntu环境中成功安装并使用支持GPU的TensorFlow,需要完成以下几个方面的配置:
#### 1. 系统需求确认
确保已启用WSL2模式,并且操作系统为Windows 11或更高版本。此外,还需要安装适用于WSL的NVIDIA驱动程序以及CUDA工具包。
- 验证是否启用了WSL2:
可以通过命令`wsl --list --verbose`查看当前使用的WSL版本[^2]。
- 安装NVIDIA WSL驱动程序:
使用以下命令下载并设置CUDA存储库文件:
```bash
sudo wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-wsl-ubuntu.pin
sudo mv cuda-wsl-ubuntu.pin /etc/apt/preferences.d/cuda-repository-pin-600
```
#### 2. CUDA和cuDNN的安装
为了使TensorFlow能够充分利用GPU加速功能,需正确安装兼容版本的CUDA和cuDNN。
- 添加CUDA官方APT仓库:
```bash
sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/7fa2af80.pub
sudo add-apt-repository "deb http://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/ /"
```
- 更新APT缓存并安装CUDA:
```bash
sudo apt-get update
sudo apt-get install -y cuda
```
- 设置环境变量以便于系统识别CUDA路径:
```bash
echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrc
echo 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc
```
#### 3. TensorFlow的安装
推荐使用Anaconda管理Python依赖关系,从而简化TensorFlow及其相关组件的安装过程。
- 创建一个新的Conda虚拟环境:
```bash
conda create -n tf_env python=3.9
conda activate tf_env
```
- 安装TensorFlow GPU版(注意选择与本地CUDA版本匹配的支持范围内的TensorFlow版本):
```bash
pip install tensorflow==2.7.0 # 对应CUDA 11.2和cuDNN 8.1[^3]
```
#### 4. 测试TensorFlow GPU支持情况
验证TensorFlow是否可以正常检测到可用的GPU设备。
- 运行如下脚本测试:
```python
import tensorflow as tf
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
# 当前分配必要显存给TF进程
tf.config.experimental.set_memory_growth(gpus[0], True)
logical_gpus = tf.config.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
print(e)
else:
print("No GPU detected.")
```
以上步骤完成后,应该可以在WSL下的Ubuntu环境中顺利运行基于GPU加速的TensorFlow应用[^1][^3].
---
阅读全文
相关推荐

















