简体   繁体   English

将keras后端从Tensorflow CPU更改为GPU

[英]Changing keras backend from tensorflow cpu to gpu

Is there a difference (in code) between keras tensorflow-cpu backend and tensorflow-gpu backend? keras tensorflow-cpu后端和tensorflow-gpu后端之间(在代码上)有区别吗? If I want to change tensorflow from cpu to gpu, what code do I need to add or what environmental variables do I need to set? 如果我想将tensorflow从cpu更改为gpu,我需要添加哪些代码或需要设置哪些环境变量?

From keras link I know that I can use tf.devices - something like the code below. 通过keras链接,我知道我可以使用tf.devices类似下面的代码。 But what if I want the whole code, not just some part to run on GPU? 但是,如果我想要整个代码,而不仅仅是一部分可以在GPU上运行,该怎么办?

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

Just uninstall tensorflow-cpu ( pip uninstall tensorflow ) and install tensorflow-gpu ( pip install tensorflow-gpu ). 只需卸载tensorflow-cpupip uninstall tensorflow )并安装tensorflow-gpupip install tensorflow-gpu )。 Now tensorflow will always use your gpu(s). 现在,tensorflow将始终使用您的GPU。

If you only want to use cpu in tensorflow-gpu set the environmental variable CUDA_VISIBLE_DEVICES so that the gpus are invisible. 如果只想在tensorflow-gpu中使用cpu,请设置环境变量CUDA_VISIBLE_DEVICES以使gpu不可见。 Before loading tensorflow do this in your script: 在加载tensorflow之前,请在脚本中执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM