首页 文章

具有Tensorflow后端的Keras可以随意使用CPU或GPU吗?

提问于
浏览
67

我在Keras上安装了Tensorflow后端和CUDA . 我想有时需要强迫Keras使用CPU . 这可以在没有在虚拟环境中安装单独的CPU Tensorflow的情况下完成吗?如果是这样的话?如果后端是Theano,可以设置标志,但我还没有听说过可通过Keras访问的Tensorflow标志 .

6 回答

  • 17

    如果你想强迫Keras使用CPU

    方式1

    import os
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
    os.environ["CUDA_VISIBLE_DEVICES"] = ""
    

    在导入Keras / Tensorflow之前 .

    方式2

    运行您的脚本

    $ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py
    

    也可以看看

  • 15

    一个相当可分的方法是使用

    import tensorflow as tf
    from keras import backend as K
    
    num_cores = 4
    
    if GPU:
        num_GPU = 1
        num_CPU = 1
    if CPU:
        num_CPU = 1
        num_GPU = 0
    
    config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
                            inter_op_parallelism_threads=num_cores, 
                            allow_soft_placement=True,
                            device_count = {'CPU' : num_CPU,
                                            'GPU' : num_GPU}
                           )
    
    session = tf.Session(config=config)
    K.set_session(session)
    

    在这里,通过 booleans GPUCPU ,我们通过严格定义允许Tensorflow会话访问的GPU和CPU的数量来指示我们是否想要使用GPU或CPU运行我们的代码 . 变量 num_GPUnum_CPU 定义此值 . num_cores 然后通过 intra_op_parallelism_threadsinter_op_parallelism_threads 设置可供使用的CPU核心数 .

    intra_op_parallelism_threads 变量指示允许计算图中单个节点中的并行操作使用(内部)的线程数 . 而 inter_ops_parallelism_threads 变量定义了可在计算图(inter)的节点之间进行并行操作的线程数 .

    allow_soft_placement 允许在满足以下任何条件的情况下在CPU上运行操作:

    • 该操作没有GPU实现

    • 没有已知或已注册的GPU设备

    • 需要与来自CPU的其他输入共存

    所有这些都是在我的类的构造函数中执行任何其他操作之前,并且可以与我使用的任何模型或其他代码完全分离 .

    注意:这需要安装 tensorflow-gpucuda / cudnn ,因为该选项用于使用GPU .

    参考文献:

  • 75

    这对我(win10)起作用,在你导入keras之前放置:

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

    根据keras tutorial,您可以简单地使用与常规tensorflow相同的 tf.device 范围:

    with tf.device('/gpu:0'):
        x = tf.placeholder(tf.float32, shape=(None, 20, 64))
        y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0
    
    with tf.device('/cpu:0'):
        x = tf.placeholder(tf.float32, shape=(None, 20, 64))
        y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0
    
  • 30

    只需导入tensortflow并使用keras,就这么简单 .

    import tensorflow as tf
    # your code here
    with tf.device('/gpu:0'):
        model.fit(X, y, epochs=20, batch_size=128, callbacks=callbacks_list)
    
  • 3

    我只花了一些时间搞清楚 . 托马的答案并不完整 . 假设你的程序是 test.py ,你想使用gpu0来运行这个程序,并保持其他gpus免费 .

    你应该写 CUDA_VISIBLE_DEVICES=0 python test.py

    注意它是 DEVICES 不是 DEVICE

相关问题