【问题标题】:How to let tensorflow use cpu and gpu at the same time如何让tensorflow同时使用cpu和gpu
【发布时间】:2020-12-26 15:44:15
【问题描述】:

我目前正在做一个项目,我需要使用 Keras pickle 来检测文本,然后我需要运行 yolov3 对象检测。 我正在根据tutorial 使用 Keras。我正在尝试根据以下tutorial.

使用 TensorFlow 应用 Yolov3

代码的工作流程是:先用 Keras,再用 yolo,两者都是分离的函数。 因此,如果我尝试在 GPU 上运行我的代码,似乎在运行 Keras 函数后我无法运行 yolo 函数,我不断收到此错误:

     Physical devices cannot be modified after being initialized")
     RuntimeError: Physical devices cannot be modified after being initialized

我在网上搜索了如何强制 Keras 使用 Cpu,发现需要放这行代码

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

在导入 Keras 之前,但是这种方法使整个代码使用 CPU。我也试过放

del os.environ['CUDA_VISIBLE_DEVICES']

之前调用yolo函数让yolo使用GPU但是没用。整个代码仍在使用 CPU 所以我的问题是:有什么方法可以让 Keras 使用 CPU,然后让 yolo 使用 GPU 或者如果我可以让 Keras 和 yolo 都使用 GPU 而不会出现之前的错误。我希望我能以正确的方式解释这个问题。

编辑:

所以首先我调用 Keras 函数

def Keras():
pickle_in = open("model_trained.p", "rb")
model = pickle.load(pickle_in)

"""some codes detect text from some image
   and save it in  variable
"""
yolo()

然后我调用yolo函数

def yolo():
  physical_devices = tf.config.experimental.list_physical_devices('GPU')
  if len(physical_devices) > 0:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)
    yolo = YoloV3(classes=6)

yolo.load_weights('./weights/yolov3.tf')
logging.info('weights loaded')

class_names = [c.strip() for c in open('./data/labels/coco.names').readlines()]
logging.info('classes loaded')

times = []

try:
    vid = cv2.VideoCapture(0)
except:
    vid = cv2.VideoCapture(0)

out = None

fps = 0.0
count = 0
while True:
    _, img = vid.read()

    if img is None:
        logging.warning("Empty Frame")
        time.sleep(0.1)
        count += 1
        if count < 3:
            continue
        else:
            break

    img_in = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_in = tf.expand_dims(img_in, 0)
    img_in = transform_images(img_in, 416)

    t1 = time.time()
    boxes, scores, classes, nums = yolo.predict(img_in)
    fps = (fps + (1. / (time.time() - t1))) / 2

    img = draw_outputs(img, (boxes, scores, classes, nums), class_names)
    img = cv2.putText(img, "FPS: {:.2f}".format(fps), (0, 30),
                      cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)
    cv2.imshow('output', img)
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()

错误的完整追溯

File "Desktop\App\yolov3.py", 
line 94, in start yolo = YoloV3(classes=number_of_c)

File "\App\yolov3_tf2\models.py", line 211, in YoloV3     
tf.config.experimental.set_memory_growth(physical_devices[0], True)

File"anaconda3\envs\yolov3gpu\lib\sitepackages\tensorflow_core\python\framework\config.py", line 494,
in set_memory_growth     context.context().set_memory_growth(device, enable)

File "anaconda3\envs\yolov3-gpu\lib\site-packages\tensorflow_core\python\eager\context.py", line 1241, in set_memory_growth

镜像策略:

import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"]="0,1" 

def Keras():
mirrored_strategy = tf.distribute.MirroredStrategy(devices["/gpu:0","/gpu:1"])
pickle_in = open("model_trained.p", "rb")
with mirrored_strategy.scope():
      model = pickle.load(pickle_in)

  """some codes detect text from some image
 and save it in  variable
 """

yolo()

【问题讨论】:

  • 您需要在问题本身中包含完整的详细信息,包括代码。
  • 我添加代码先生
  • 把你的 yolo() 函数的前三行去掉再试一次,我觉得不需要。
  • 我在先生之前试过这个,我在这行代码中遇到了同样的错误 yolo = YoloV3(classes=number_of_c)
  • 那么请添加错误的完整回溯

标签: python tensorflow keras yolo


【解决方案1】:

可以在 GPU 上运行整个脚本。

您需要以下代码:

import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"

如果您有多个 GPU,则可以使用 mirrored_strategy:

import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2,..." #Num of your GPUs

mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1", ...])

然后将您的模型放入范围内:

with mirrored_strategy.scope():
    model = Sequential()
    model.add(...)

【讨论】:

  • 我的系统中有两个 GPU(RTX 2070s)。先生,我尝试了您的解决方案,但出现此错误: raise ValueError(handle` is not available outside the replica context ValueError: handle is not available outside the replica context or a tf.distribute.Strategy.update() call.跨度>
  • 你能告诉我,你的代码包括mirrored_strategy吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2018-01-02
  • 2020-02-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
相关资源
最近更新 更多