title: Is there a way to change GPU / CPU on tensorflow during code execution?
body: <p>I have 2 tensorflow (1.15.4) models running sequentially. The output from the first model will be fed into the second model.
  Is there a way to run the first model using CPU and run the second one using GPU in one python script?</p>
  <p>To simplify it, I tried a sample script like below</p>
  <pre><code>import os
  import tensorflow as tf
  os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;]=&quot;-1&quot;
  print(tf.test.is_gpu_available())
  os.environ.pop(&quot;CUDA_VISIBLE_DEVICES&quot;)
  os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;]=&quot;0&quot;
  print(tf.test.is_gpu_available())
  </code></pre>
  <p>However, both print results are <code>False</code> .</p>
  <p>Is it possible to switch the device type in the middle of execution of a piece of codes?</p>
  <p>Thank you!</p>
  <hr />
  <p>Update:</p>
  <p>According the comments, I tried the tf.device as follows</p>
  <pre><code>import tensorflow as tf
  
  with tf.device(&quot;/CPU:0&quot;):
      code1
  
  with tf.device('GPU:0'):
      code2
  </code></pre>
  <p>However, both code1 and code2 are run on CPU. Is there anything I am missing?</p>
  <p>Thank you</p>