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)
6 回答
如果你想强迫Keras使用CPU
方式1
在导入Keras / Tensorflow之前 .
方式2
运行您的脚本
也可以看看
https://github.com/keras-team/keras/issues/152
https://github.com/fchollet/keras/issues/4613
一个相当可分的方法是使用
在这里,通过
booleans
GPU
和CPU
,我们通过严格定义允许Tensorflow会话访问的GPU和CPU的数量来指示我们是否想要使用GPU或CPU运行我们的代码 . 变量num_GPU
和num_CPU
定义此值 .num_cores
然后通过intra_op_parallelism_threads
和inter_op_parallelism_threads
设置可供使用的CPU核心数 .intra_op_parallelism_threads
变量指示允许计算图中单个节点中的并行操作使用(内部)的线程数 . 而inter_ops_parallelism_threads
变量定义了可在计算图(inter)的节点之间进行并行操作的线程数 .allow_soft_placement
允许在满足以下任何条件的情况下在CPU上运行操作:该操作没有GPU实现
没有已知或已注册的GPU设备
需要与来自CPU的其他输入共存
所有这些都是在我的类的构造函数中执行任何其他操作之前,并且可以与我使用的任何模型或其他代码完全分离 .
注意:这需要安装
tensorflow-gpu
和cuda
/cudnn
,因为该选项用于使用GPU .参考文献:
What do the options in ConfigProto like allow_soft_placement and log_device_placement mean?
Meaning of inter_op_parallelism_threads and intra_op_parallelism_threads
这对我(win10)起作用,在你导入keras之前放置:
根据keras tutorial,您可以简单地使用与常规tensorflow相同的
tf.device
范围:只需导入tensortflow并使用keras,就这么简单 .
我只花了一些时间搞清楚 . 托马的答案并不完整 . 假设你的程序是
test.py
,你想使用gpu0来运行这个程序,并保持其他gpus免费 .你应该写
CUDA_VISIBLE_DEVICES=0 python test.py
注意它是
DEVICES
不是DEVICE