📜  获取 gpu 名称 tensorflow 和 pytorch - Python (1)

📅  最后修改于: 2023-12-03 15:11:50.335000             🧑  作者: Mango

获取 GPU 名称 TensorFlow 和 PyTorch

在使用 TensorFlow 或 PyTorch 进行深度学习时,使用 GPU 可以大大缩短模型训练时间。在本文中,将介绍如何通过 Python 获取 GPU 名称。

获取 GPU 名称

要获取 GPU 名称,可以使用 cudatorchtensorflow 的版本信息。以下是获取 GPU 名称的代码片段:

PyTorch
import torch

if torch.cuda.is_available():
    gpu_count = torch.cuda.device_count()
    for i in range(gpu_count):
        print(torch.cuda.get_device_name(i))
else:
    print("No GPU available")

上述代码使用 torch.cuda.is_available() 判断是否有可用的 GPU。如果有,使用 torch.cuda.device_count() 获取可用的 GPU 数量。随后使用 torch.cuda.get_device_name(i) 循环获取每个 GPU 的名称进行打印。

TensorFlow
import tensorflow as tf

if tf.test.is_gpu_available():
    gpu = tf.config.list_physical_devices('GPU')
    for device in gpu:
        print(tf.config.experimental.get_device_name(device))
else:
    print("No GPU available")

上述代码通过 tf.test.is_gpu_available() 判断是否有可用的 GPU。如果有,使用 tf.config.list_physical_devices('GPU') 获取可用的 GPU 设备列表。随后循环打印每个 GPU 设备的名称。

总结

通过本文可以了解如何获取 GPU 名称,从而方便在 TensorFlow 或 PyTorch 中使用 GPU 进行模型训练。