使用TensorFlow库的list_local_devices()函数生成Python中的本地设备列表
发布时间:2024-01-12 06:30:21
在TensorFlow中,可以使用tf.config.experimental.list_local_devices()函数来生成Python中的本地设备列表。该函数返回一个列表,其中包含可用于TensorFlow计算的本地设备。
下面是一个使用TensorFlow库的list_local_devices()函数的例子:
import tensorflow as tf
# 获取本地设备列表
devices = tf.config.experimental.list_local_devices()
# 打印所有设备信息
for device in devices:
print(device.name, device.device_type)
# 打印GPU设备信息
gpus = [device.name for device in devices if device.device_type == 'GPU']
print("可用的GPU设备:", gpus)
上述代码首先导入tensorflow库,然后使用tf.config.experimental.list_local_devices()函数获取本地设备列表。然后,可以使用for循环遍历设备列表,并打印每个设备的名称和设备类型。
在打印设备信息后,我们可以进一步筛选出GPU设备。在上述示例中,我们使用了一个列表推导式来找到设备类型为'GPU'的设备,并将其名称存储在名为gpus的列表中。
使用list_local_devices()函数的输出类似于以下内容:
/device:CPU:0 CPU /device:GPU:0 GPU /device:GPU:1 GPU ...
在上述示例中,我们打印了所有设备的名称和设备类型。然后,我们筛选了设备类型为'GPU'的设备,并打印了可用的GPU设备列表。
这些信息对于决定在TensorFlow中分配计算任务给哪些设备非常有用。
