【问题标题】:How to Know if Keras is using GPU or CPU如何知道 Keras 使用的是 GPU 还是 CPU
【发布时间】:2020-08-14 15:41:42
【问题描述】:

有什么方法可以检查 Keras 框架是使用 GPU 还是 CPU 来训练模型?

我正在使用 keras 在 GPU 上训练我的模型,但它太慢了,我不确定它是使用 CPU 还是 GPU 进行训练。

【问题讨论】:

    标签: python tensorflow keras tensorflow2.0


    【解决方案1】:

    首先,您需要找到 GPU 设备:

    physical_device = tf.config.experimental.list_physical_devices('GPU')
    print(f'Device found : {physical_device}')
    

    然后您可以使用以下代码检查您的 GPU 设备是否已用于训练:

    tf.config.experimental.get_memory_growth(physical_device[0])
    

    如果此代码返回 False 或不返回任何内容,那么您可以在下面运行此代码来设置 GPU 进行训练

    tf.config.experimental.set_memory_growth(physical_device[0],True)
    

    【讨论】:

    • get_memory_growth 和 set_memory_growth 与使用的 GPU 有什么关系?
    • set_memory_growth 用于更换火车设备。例如:set_memory_growth(device1,True) 会将训练设备更改为 device1,它将使用 gpu 内存。 get_memory_growth 用于检查您是否为设备设置了内存增长。
    • set_memory_growth 的文档没有提到任何关于更改火车设备tensorflow.org/api_docs/python/tf/config/experimental/… 所以我认为你的答案不正确
    【解决方案2】:

    首先让我们确保 tensorflow 正在检测您的 GPU。运行下面的代码。如果 GPU 数量 = 0,则表示未检测到您的 GPU。要让 tensorflow 使用 GPU,您需要安装 Cuda 工具包和 Cudnn。如果没有检测到 GPU,并且您正在使用 Anaconda,请重新安装带有 Conda 的 tensorflow。它会自动安装工具包和 Cudnn。当你使用 Pip 安装 tensorflow 时,Pip 不会安装这些。

    import tensorflow as tf
    from tensorflow.python.client import device_lib
    print(device_lib.list_local_devices())
    print(tf.__version__)
    print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
    tf.test.is_gpu_available()
    !python --version
    

    【讨论】:

    • 我认为上面的代码仅用于检查是否检测到GPU,我的电脑可能检测到GPU但在CPU上训练。
    • 我的经验是,如果它检测到它,它就会使用它。如果没有检测到,那么它只会使用 CPU
    【解决方案3】:

    这里是参考演示:

    import tensorflow as tf
    physical_device = tf.config.experimental.list_physical_devices('GPU')
    print(f'Device found : {physical_device}') 
    

    【讨论】:

      猜你喜欢
      • 2019-12-01
      • 2012-02-27
      • 2020-07-18
      • 2017-12-17
      • 2021-11-20
      • 2017-09-04
      • 2019-04-19
      • 1970-01-01
      • 2012-11-21
      相关资源
      最近更新 更多