c.Parsi
c.Parsi

Reputation: 771

Force Keras with Tensorflow backend to run on GPU

I have written a function that extracts features using vgg16 network using keras with tensorflow as backend. The problem is it by default runs it on CPU instead of GPU. I do have a GPU compatible machine and a few days ago another code (for training) was using GPU. I added this code snippet to force it to GPU but still it does not work.

import tensorflow as tf
from keras import backend as K
GPU = True
CPU = False
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)

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())}

this is the output it provides after running the feature extraction

Backend Qt5Agg is interactive backend. Turning interactive mode on.
Using TensorFlow backend.
[name: "/cpu:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 5806448485889010842
]

and here is the code that extracts the features (does work properly but runs on CPU)

modelname  = 'vgg16'
Network    = MODELS[modelname]
model      = Network(weights="imagenet", include_top=False, input_shape=inputShape)
x          = preprocess(img_4D.copy())
features   = model.predict(np.float64(x))

Upvotes: 2

Views: 1826

Answers (1)

Farhan
Farhan

Reputation: 439

Have you tried uninstalling the CPU version of Tensorflow so that the only version on your computer is the GPU version?

Upvotes: 1

Related Questions