2017-06-23 69 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?