9113303
9113303

Reputation: 872

Running python code consumes GPU. why?

This is my python code for a model prediction.

import csv
import numpy as np
np.random.seed(1)
from keras.models import load_model
import tensorflow as tf
import pandas as pd
import time


output_location='Desktop/result/'
 #load model
global graph
graph = tf.get_default_graph()
model = load_model("newmodel.h5")
def Myfun():
        ecg = pd.read_csv('/Downloads/model.csv')
        X = ecg.iloc[:,1:42].values
        y = ecg.iloc[:,42].values

        from sklearn.preprocessing import LabelEncoder
        encoder =  LabelEncoder()
        y1 = encoder.fit_transform(y)

        Y = pd.get_dummies(y1).values


        from sklearn.model_selection import train_test_split
        X_train,X_test, y_train,y_test = train_test_split(X,Y,test_size=0.2,random_state=0) 
        t1= timer()
        with graph.as_default():
            prediction = model.predict(X_test[0:1])
            diff=timer()-t1
            class_labels_predicted = np.argmax(prediction)
            filename1=str(i)+"output.txt"
            newfile=output_location+filename1
            with open(str(newfile),'w',encoding = 'utf-8') as file:

                file.write(" takes %f seconds time.  predictedclass is %s \n" %(diff,class_labels_predicted))
        return class_labels_predicted

for i in range(1,100):
    Myfun()

My system GPU is of size 2GB. While running this code ,nvidia-smi -l 2 shows it consumes 1.8 GB of GPU. And 100 files are getting as a result. Soon after the task completes again GPU utilisation turns to 500MB. I have tensorflow and keras GPU version installed in my system. My Question is:

  1. Why does this code runs on GPU. Does the complete code uses GPU or its only for importing libraries such as keras-gpu and tensorflow-gpu?

This is the GPU consumption while starting the task

This shows GPU utilization (1.8 out of 2GB)

Upvotes: 0

Views: 80

Answers (2)

Marco Visibelli
Marco Visibelli

Reputation: 359

You can force Keras to run on CPU only

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""

Upvotes: 1

Vladimir Poghosyan
Vladimir Poghosyan

Reputation: 551

As I can see from your code, you are using Keras and Tensorflow. From Keras F.A.Q.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

Upvotes: 1

Related Questions