本文在win11环境下安装GPU加速的tensorflow


前言

本文在win11环境下安装GPU加速的tensorflow
相比于CPU版本,需要安装cuda cudnn
使用gpu:GTX4060
安装工具:anaconda


一、安装包

管理员模式打开anaconda prompt
命令如下:

conda create --name lab7-tf-gpu python=3.9.21
conda activate lab7-tf-gpu

conda install -c conda-forge numpy=1.23.5 scipy=1.9.3 scikit-learn=1.2.2
conda install -c conda-forge cudatoolkit=11.2.2 cudnn=8.1.0
pip install tensorflow==2.10.1
conda install ipykernel

其中numpy必须要降级否则可能有问题

二、验证

代码如下:

import sys
print(f"Python版本: {sys.version.split()[0]}") #Python版本: 3.9.21

import tensorflow as tf

print(f"TensorFlow 版本: {tf.__version__}") #TensorFlow 版本: 2.10.1
print(f"GPU 可用性: {tf.config.list_physical_devices('GPU')}") #GPU 可用性: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
print(f"CUDA 版本: {tf.sysconfig.get_build_info()['cuda_version']}") #CUDA 版本: 64_112
print(f"cuDNN 版本: {tf.sysconfig.get_build_info()['cudnn_version']}") #cuDNN 版本: 64_8

三、对比CPU与GPU的运行速度

代码如下

import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"  # 屏蔽TensorFlow日志
import time
import numpy as np
import tensorflow as tf

# 创建大型单精度浮点矩阵(10000x10000)
matrix = np.random.rand(10000, 10000).astype(np.float32)

# 预热:避免首次计算的初始化时间干扰
print("执行预热计算...")
with tf.device('/GPU:0'):
    _ = tf.matmul(matrix, matrix)  # GPU预热
with tf.device('/CPU:0'):
    _ = tf.matmul(matrix, matrix)  # CPU预热

# CPU计算
start_cpu = time.time()
with tf.device('/CPU:0'):
    result_cpu = tf.matmul(matrix, matrix)
end_cpu = time.time()
cpu_time = end_cpu - start_cpu

# GPU计算
start_gpu = time.time()
with tf.device('/GPU:0'):
    result_gpu = tf.matmul(matrix, matrix)
end_gpu = time.time()
gpu_time = end_gpu - start_gpu

# 输出结果
print(f"CPU 矩阵乘法耗时: {cpu_time:.2f}秒")
print(f"GPU 矩阵乘法耗时: {gpu_time:.2f}秒")
print(f"GPU加速比: {cpu_time / gpu_time:.1f}倍")

'''
执行预热计算...
CPU 矩阵乘法耗时: 1.46秒
GPU 矩阵乘法耗时: 0.14秒
GPU加速比: 10.5倍
'''

参考

1.版本对应关系

https://blog.csdn.net/ly869915532/article/details/124542362

Logo

更多推荐