2017-06-23 22 views
0

我知道Tensorflow可以通过"/cpu0""/gpu0"明确地将计算放置在任何设备上。但是,这是硬编码的。有没有办法用内置的API迭代所有可见的设备?在Tensorflow中循环cpu和gpu设备

+0

【如何获得tensorflow当前可用的GPU?](HTTPS的可能重复: //stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow) –

回答

0

这里是你想拥有的一切:

import tensorflow as tf 
from tensorflow.python.client import device_lib 

def get_all_devices(): 
    local_device_protos = device_lib.list_local_devices() 
    return [x.name for x in local_device_protos] 

all_devices = get_all_devices() 
for device_name in all_devices: 
    with tf.device(device_name): 
     if "cpu" in device_name: 
      # Do something 
      pass 
     if "gpu" in device_name: 
      # Do something else 
      pass 

代码是从最好的答案在这里启发:How to get current available GPUs in tensorflow?