欢迎访问宙启技术站
智能推送

使用list_local_devices()函数在Python中生成TensorFlow本地设备列表的实例

发布时间:2024-01-12 06:29:13

在TensorFlow中,tf.config.list_local_devices()函数返回当前本地计算机上的所有TensorFlow设备列表。这些设备可以是物理设备(如CPU和GPU)或虚拟设备(如TensorFlow Lite设备)。

以下是一个使用list_local_devices()函数生成本地设备列表的示例:

import tensorflow as tf

# 检查TensorFlow版本
print("TensorFlow version:", tf.__version__)

# 列出本地设备
devices = tf.config.list_local_devices()

# 打印设备信息
for device in devices:
    print(device.name, device.device_type)

运行上述代码,将输出计算机上所有TensorFlow设备的名称和设备类型。例如,可以获得类似于以下输出:

TensorFlow version: 2.6.0
/device:CPU:0 CPU
/device:GPU:0 GPU

上述输出显示计算机上具有一个CPU设备(device:CPU:0)和一个GPU设备(device:GPU:0)。在实际运行时,设备的数量和类型将根据计算机的配置而有所不同。

我们还可以使用list_local_devices()函数来查找特定类型的设备。例如,我们只想查找GPU设备,可以使用以下代码:

import tensorflow as tf

# 列出本地设备
devices = tf.config.list_local_devices()

# 查找GPU设备
gpu_devices = [device.name for device in devices if device.device_type == "GPU"]

# 打印GPU设备名称
for gpu_device in gpu_devices:
    print("GPU device:", gpu_device)