How to feed grayscale images into a pretrained neural network models? - tensorflow

Noob here . I have been working with grayscale images for mitosis classification Here's a sample image I'm working with . I have employed VGGnet for achieving this. I've some doubts about how my grayscale image should be fed into the neural network. I've read the documentation of VGGnet about being trained on colored images on Imagenet.
I read the images using cv2.imread() and by squeezing into an array. I found its shape to be (227,227,3). Shouldn't it be (227,227,1) when I'm handling with grayscale images ? Model accuracy was also found to be only 50% . I'm wondering if it's something wrong with the dataset itself or VGGnet isn't suitable for this purpose. Or should I use some other method to read these images to get grayscale images?
I have tried the solutions listed in similar questions . Am I reading the images in the right way?
I'm sharing my code here.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Display Image data
from PIL import Image
import cv2
from google.colab import drive
drive.mount('/content/drive')
mitotic_image = Image.open('/content/drive/MyDrive/Medical/actualmito1/trainactmito01.jpg')
nonmitotic_image=Image.open('/content/drive/MyDrive/Medical/actualnonmito1/trainactnonmito01.jpg')
# subplotting image data
fig = plt.figure(figsize=(15,9))
ax1 = fig.add_subplot(1, 2, 1)
img_plot = plt.imshow(nonmitotic_image, cmap = plt.cm.bone)
ax1.set_title("Non-Mitotic Image")
ax2 = fig.add_subplot(1, 2, 2)
img_plot = plt.imshow(mitotic_image, cmap = plt.cm.bone)
ax2.set_title("Mitotic Image")
plt.show()
import os
yes = os.listdir("/content/drive/MyDrive/Medical/actualmito1")
no = os.listdir("/content/drive/MyDrive/Medical/actualnonmito1")
data = np.concatenate([yes, no])
target_yes = np.full(len(yes), 1)
target_no = np.full(len(no), 0)
# Image Target
data_target = np.concatenate([target_yes, target_no])
# Generate Image Data
img = cv2.imread("/content/drive/MyDrive/Medical/actualmito1/trainactmito01.jpg")
mitosis = cv2.resize(img,(32,32))
plt.imshow(mitosis)
X_data = []
yes = os.listdir("/content/drive/MyDrive/Medical/actualmito1")
for file in yes:
img = cv2.imread("/content/drive/MyDrive/Medical/actualmito1/" + file)
# resizing image data to 32x32
img = cv2.resize(img, (224,224))
X_data.append(img) # This will store list of all image data in an array
no = os.listdir("/content/drive/MyDrive/Medical/actualnonmito1")
for file in no:
img = cv2.imread("/content/drive/MyDrive/Medical/actualnonmito1/" + file)
# resizing image data to 32x32
img = cv2.resize(img, (224,224))
X_data.append(img) # This will store list of all image data in an array
X = np.squeeze(X_data)
X.shape
# Image Pixel Normalization
X = X.astype('float32')
X /= 255
X.shape
# Train & Test Data
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, data_target, test_size = 0.1,
random_state = 3)
x_train2, x_val, y_train2, y_val = train_test_split(x_train, y_train, test_size = 0.15,
random_state = 3)
# VGG16 - Transfer Learning
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Conv2D, GlobalAveragePooling2D, Flatten, ZeroPadding2D,
Dropout, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.applications import VGG16
def build_model():
#use Imagenet = pre-trained models weights called knowledge transfer
# image_shape = 32x32x3
vgg16_model = VGG16(weights = 'imagenet', include_top = False, input_shape=(224,224,3))
# Input Layer
model = Sequential()
# paadding = 'same' = ZeroPadding
model.add(Conv2D(filters=3, kernel_size=(3,3), padding='same', input_shape = (224,224,3)))
# add transfer learning model
model.add(vgg16_model)
# Average Pooling Layer
model.add(GlobalAveragePooling2D())
model.add(BatchNormalization())
model.add(Dropout(0.5))
# Fully Connected Layer
model.add(Dense(units = 512, activation='relu'))
model.add(Dropout(0.5))
# Output Layer
model.add(Dense(units = 1, activation='sigmoid'))
model.compile(optimizer = 'Adam', loss = 'binary_crossentropy', metrics = ['Accuracy'])
return model
model = build_model()
model.summary()
from tensorflow.keras import callbacks
filepath = "/content/drive/MyDrive/BestModelMRI3.hdf5"
checkpoint = callbacks.ModelCheckpoint(filepath, monitor = 'val_loss', save_best_only = True,
mode = 'min',verbose = 1)
import datetime
import keras
import os
logdir = os.path.join("/content/drive/MyDrive/MRI_logs",
datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = keras.callbacks.TensorBoard(logdir)
history = model.fit(x_train2, y_train2, epochs = 200, batch_size = 32, shuffle = True,
validation_data = (x_val, y_val), callbacks = [checkpoint, tensorboard_callback],verbose= 1)
model.load_weights("/content/drive/MyDrive/BestModelMRI3.hdf5")
model.evaluate(x_test, y_test)
predictions = model.predict(x_test)
yhat = np.round(predictions)
from sklearn.metrics import confusion_matrix, classification_report
confusion_matrix(y_test, yhat)
sns.heatmap(confusion_matrix(y_test, yhat), annot = True, cmap = 'RdPu')
print(classification_report(y_test, yhat))

VGG model was trained on RGB images. CV2 reads in images as BGR. so add code
img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
to convert BGR to RGB. Also VGG requires the pixels to be in the range -1 to +1 so scale with
X=X/127.5 -1

Related

Low validation accuracy but the train have high accuracy, also the validation loss so high

i have a question, when im creating the model, why it have high accuracy and low loss, but the validation accuracy low and validation loss so high.
Any recommend way to improve this?
It took 256 samples, validate on 65 samples.
This is the code that i used to
import numpy as np
import cv2
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
# from tensorflow.keras.models import Sequential
from keras.models import Sequential
# from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.layers import Conv2D,MaxPooling2D,Dense, Dropout, Activation, Flatten
# from tensorflow.keras.optimizers import Adam,RMSprop,SGD
from keras.optimizers import Adam , RMSprop, SGD
import pickle
from streamlit_webrtc import webrtc_streamer
################################################################
path = 'DatasetsBatik'
testRatio = 0.2
validationRatio = 0.2
imageDimension =(32,32,3)
batchSizeVal=2
epochsVal=200
stepsPerEpochVal=200
################################################################
images=[]
classNumber =[]
myList = os.listdir(path)
print("Total Number of Classes Detected" , " : " , len(myList))
NumberOfClasses =len(myList)
print("Importing Classes ....")
for x in range(0,NumberOfClasses):
#0 Representing Kawung,
#1 Representing Megamendung,
#2 Representing Parang,
#3 Representing Sekar Jagad,
#4 Representing Simbut,
myPicList = os.listdir(path+"/"+str(x))
for y in myPicList:
currentImage = cv2.imread(path+"/"+str(x)+"/"+y)
currentImage = cv2.resize(currentImage, (imageDimension[0],imageDimension[1]) )
images.append(currentImage)
classNumber.append(x)
print(x,end = " " )
print("")
print(len(classNumber))
images = np.array(images)
classNumber = np.array(classNumber)
# print(images.shape)
# print(classNumber.shape)
### Split Data
X_train,X_test,Y_train,Y_test = train_test_split(images,classNumber,test_size = testRatio)
X_train,X_validation,Y_train,Y_validation= train_test_split(X_train,Y_train,test_size = validationRatio)
print("x_train.shape = " + str(X_train.shape))
print("x_test.shape = " +str(X_test.shape))
print("x_validation.shape = "+str(X_validation.shape))
NumberOfSamples=[]
for x in range(0,NumberOfClasses):
# print(len(np.where(Y_train ==x)[0]))
NumberOfSamples.append(len(np.where(Y_train==x)[0]))
print("Number Of Samples : " +str(NumberOfSamples))
plt.figure(figsize=(10,5))
plt.bar(range(0,NumberOfClasses),NumberOfSamples)
plt.title("Number of Images for each Class")
plt.xlabel("Class ID")
plt.ylabel("Number of Images")
plt.show()
# print(X_train)
def PreProcessing(img):
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = cv2.equalizeHist(img)
img = img/255
return img
# img = X_train[30]
# img = cv2.resize(img,(300,300))
# cv2.imshow("PreProcessed",img)
# cv2.waitKey(0)
X_train=np.array(list(map(PreProcessing,X_train)))
# print(X_train)
X_test=np.array(list(map(PreProcessing,X_test)))
X_validation=np.array(list(map(PreProcessing,X_validation)))
# print(X_train.shape)
X_train = X_train.reshape(X_train.shape[0],X_train.shape[1],X_train.shape[2],1)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1],X_test.shape[2],1)
X_validation = X_validation.reshape(X_validation.shape[0],X_validation.shape[1],X_validation.shape[2],1)
# print(X_train.shape)
dataGen = ImageDataGenerator(width_shift_range=0.1,height_shift_range=0.1,zoom_range=0.2,shear_range=0.1,rotation_range=10)
dataGen.fit(X_train)
Y_train = to_categorical(Y_train,NumberOfClasses)
Y_test = to_categorical(Y_test,NumberOfClasses)
Y_validation = to_categorical(Y_validation,NumberOfClasses)
def myModel():
NumberOfFilters1 = 128
NumberOfFilters2 = 256
sizeOfFilter1=(5,5)
sizeOfFilter2=(3,3)
sizeOfPool=(2,2)
NumberOfNode=128
model = Sequential()
model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,input_shape=(imageDimension[0],imageDimension[1],1),activation='relu')))
model.add(Dropout(0.5))
model.add(MaxPooling2D(pool_size=sizeOfPool))
# model.add((Conv2D(NumberOfFilters1,sizeOfFilter1,activation='relu')))
# model.add(MaxPooling2D(pool_size=sizeOfPool))
# model.add(Dropout(0.5))
model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
model.add(MaxPooling2D(pool_size=sizeOfPool))
model.add(Dropout(0.5))
# model.add((Conv2D(NumberOfFilters2,sizeOfFilter2,activation='relu')))
# model.add(MaxPooling2D(pool_size=sizeOfPool))
# model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(NumberOfNode,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NumberOfClasses,activation='softmax'))
model.compile(Adam(lr=0.0005),loss='categorical_crossentropy',metrics=['accuracy'])
return model
model = myModel()
print(model.summary())
history = model.fit_generator(dataGen.flow(X_train,Y_train,batch_size=batchSizeVal),steps_per_epoch=stepsPerEpochVal,epochs=epochsVal,validation_data=(X_validation,Y_validation),shuffle=1)
# history= model.fit(X_train, Y_train, batch_size=batchSizeVal,epochs=epochsVal,verbose=1,validation_data=(X_validation, Y_validation))
plt.figure(1)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['training','validation'])
plt.title('Loss')
plt.xlabel('epoch')
plt.figure(2)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['training','validation'])
plt.title('Accuracy')
plt.xlabel('epoch')
plt.show()
score= model.evaluate(X_test,Y_test,verbose=0)
print('Test Score =',score[0])
print('Score Accuracy = ',score[1])
print(score)
# print(model.metrics_names)
pickle_out=open("10_TestModel4","wb")
pickle.dump(model,pickle_out)
pickle_out.close()
This is the result that i have now
Epoch 1
Finish,Epoch 200
I have tried to remove or add hidden layer, and also try some different learning rate, epoch, batch size, steps per epoch, adding drop out for the layer . Any recommend would be very helpfull, thankyou.

Why is the Accuracy Different in my PC From Kaggle When Using the Same Code

I am writing a watermark detection algorithm, and I've tried a code from Kaggle which fine-tunes a ResNet, but when I run the same code in Jupyter notebook, I get 50% accuracy when the sample code in Kaggle has around 97% accuracy. I don't have a GPU installed on my PC, and I changed the batch size to 32. Do you know why I get 40% lower accuracy?
My Code:
import tensorflow as tf
import numpy as numpy
import os
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import RMSprop
from PIL import Image
basedir = "/home/mahsa/Kaggle/archive/wm-nowm"
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
traindir = os.path.join(basedir,'train') # root for training
validdir = os.path.join(basedir,'valid') # root for testing
traingenerator = ImageDataGenerator(rescale=1./255)
validgenerator = ImageDataGenerator(rescale=1./255)
train_data = traingenerator.flow_from_directory(traindir,target_size=(150,150),batch_size=100,class_mode="binary")
valid_data = validgenerator.flow_from_directory(validdir,target_size=(150,150),batch_size=100,class_mode="binary")
existing = tf.keras.applications.InceptionResNetV2 (input_shape=(150, 150, 3),include_top=False, pooling='max', weights='imagenet')
#for layer in existing.layers:
# layer.trainable = False
#existing.summary()
last = existing.get_layer("mixed_7a")
last_output = last.output
# Flatten the output layer to 1 dimension
x = tf.keras.layers.Flatten()(last_output)
x = tf.keras.layers.Dropout(0.25)(x)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = tf.keras.layers.Dense(128, activation='relu')(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
# Add a final sigmoid layer for classification
x = tf.keras.layers.Dense (1, activation='sigmoid')(x)
model = tf.keras.Model( existing.input, x)
model.compile(optimizer=RMSprop(lr=0.001),
loss='binary_crossentropy',
metrics = ['accuracy'])
history = model.fit(train_data,
validation_data=valid_data,
steps_per_epoch=150,
epochs=60,
validation_steps=50,
verbose=2)
I found out that the problem was batch_size, I increased the batch_size to 100, it took about 1.5 day to train the model but I got 99% accuracy.

'Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (120000, 0)

I made an image classification system which detects plant leaf diseases using the PlantVillage dataset. I created the whole process starting from the preprocessing to the model building but when I try to run the program, the above error pops up. Now I tried a lot of things and frankly I do not want to mess with the dataset in colab so could anyone please help me out with this, I will be ever so grateful.
This is the preprocessing part of my code.
import numpy as np
import pickle
import cv2
import os
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from os import listdir
from sklearn.preprocessing import LabelBinarizer
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation, Flatten, Dropout, Dense
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.preprocessing import image
from keras.preprocessing.image import img_to_array
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
from google.colab import drive
drive.mount('/content/drive')
#Resize the image to match the input shape of the layer
default_image_size = tuple((256, 256))
image_size = 0
#dataset directory
directory_root = '/content/drive/MyDrive/proj/PlantVillage'
width = 256
height = 256
depth = 3
def convert_image_to_array(image_dir):
#loads an image from the directory if the image exists
image = cv2.imread(image_dir)
if image is not None:
#changes the dimensions of the image, width or height or both and also maintains the original aspect ratio in the resized version
image = cv2.resize(image, default_image_size)
return img_to_array(image)
else:
#if the image does not exist, it returns an empty array
return np.array([])
image_list, label_list = [], []
print("[INFO] Loading Images...")
root_dir = listdir(directory_root)
for plant_folder in root_dir:
plant_disease_folderlist = listdir(f"{directory_root}/{plant_folder}")
for plant_disease_folder in plant_disease_folderlist:
print(f"[INFO] Processing {plant_disease_folder} ...")
plant_disease_image_list = listdir(f"{directory_root}/{plant_folder}/")
for image in plant_disease_image_list[:200]:
image_directory = f"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}"
if image_directory.endswith(".jpg") == True or image_directory.endswith(".JPG") == True:
image_list.append(convert_image_to_array(image_directory))
label_list.append(plant_disease_folder)
print("[INFO] Image Loading Complete!")
#transforms the resized image data into numpy array
np_image_list = np.array(image_list, dtype = np.float16) / 255.0
#checks for the number of images loaded for training
image_size = len(image_list)
print(f"Total number of images: {image_size}")
#each class or label is assigned a unique value for training
label_binarizer = LabelBinarizer()
image_labels = label_binarizer.fit_transform(label_list)
#dumping the labels in the pkl file so it can be used for predictions
pickle.dump(label_binarizer,open('plantlabel.pkl', 'wb'))
n_classes = len(label_binarizer.classes_)
print("Total number of classes: ", n_classes)
print("Labels: ", label_binarizer.classes_)
print("[INFO] Splitting Data Into Training and Testing Set...")
#splitting the data with a 0.2 split ratio
x_train, x_test, y_train, y_test = train_test_split(np_image_list, image_labels, test_size=0.2, random_state = 42)
#data augmentation is used to generate more images in the dataset. The different operations are applied on the image to diversify the dataset so it performs well with unseen images
#only the object is created here, this will be used later in the training
aug = ImageDataGenerator(rotation_range=25,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode="nearest")
Now I built the model with keras and added the layers, everything was recognized correctly until this part.
EPOCHS = 10
LR = 1e-3
BATCH_SIZE = 32
WIDTH = 256
HEIGHT = 256
DEPTH = 3
#creating the model
inputShape = (HEIGHT, WIDTH, DEPTH)
chanDim = -1
if K.image_data_format() == "channels_first":
inputShape = (DEPTH, HEIGHT, WIDTH)
chanDim = -1
model = Sequential()
model.add(Conv2D(32, (3, 3), padding = "same", input_shape = inputShape))
model.add(Activation("relu"))
model.add(BatchNormalization(axis = chanDim))
model.add(MaxPooling2D(pool_size = (3, 3)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding = "same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis = chanDim))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), padding = "same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis = chanDim))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation("relu"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(n_classes))
model.add(Activation("softmax"))
model.summary()
opt = Adam(lr = LR, decay = LR/EPOCHS)
model.compile(loss="binary_crossentropy", optimizer=opt,metrics=["accuracy"])
print("[INFO] Training Begins...")
history = model.fit_generator(
aug.flow(x_train, y_train, batch_size=BATCH_SIZE),
validation_data=(x_test, y_test),
steps_per_epoch=len(x_train) // BATCH_SIZE,
epochs=EPOCHS, verbose=1
)
print("[INFO] Training Complete...")
Here at the aug.flow(x_train, batch_size=BATCH_SIZE,...) part, the error occurs. The error is as follows.
ValueError Traceback (most recent call last)
<ipython-input-13-a2fb6e262c72> in <module>()
4 print("[INFO] Training Begins...")
5 history = model.fit_generator(
----> 6 aug.flow(x_train, y_train, batch_size=BATCH_SIZE),
7 validation_data=(x_test, y_test),
8 steps_per_epoch=len(x_train) // BATCH_SIZE,
2 frames
/usr/local/lib/python3.6/dist-packages/keras_preprocessing/image/numpy_array_iterator.py in __init__(self, x, y, image_data_generator, batch_size, shuffle, sample_weight, seed, data_format, save_to_dir, save_prefix, save_format, subset, dtype)
124 raise ValueError('Input data in `NumpyArrayIterator` '
125 'should have rank 4. You passed an array '
--> 126 'with shape', self.x.shape)
127 channels_axis = 3 if data_format == 'channels_last' else 1
128 if self.x.shape[channels_axis] not in {1, 3, 4}:
ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (120000, 0))
I am training on only 1500 images because the purpose of my project was only to build a model. I just need to get the training done. I hope someone can aid me with this. Thank you.

transfer learning of Inception v3 returns the same predictions

I have tried to customize inception to classify. I used the cat, dog, human and other to classify cat, dog, human ( collection of family photos) and other (mostly natural scenes) I have about 2000 dog, 1000 cat, 7000 human and 3000 images split 80:20 among the train and validate. The essence of model is as below. When I train the training accuracy is close to 97% and validation accuracy is ~90%.
import os
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.applications.inception_v3 import InceptionV3
local_weights_file = 'C:/users/sethr/education/Healthcare/imagedetect/modelimageadvance /inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(input_shape = (150, 150,3), include_top = False, weights = `enter code here`local_weights_file)
for layer in pre_trained_model.layers:
layer.trainable = False
# pre_trained_model.summary()
last_layer = pre_trained_model.get_layer('mixed7')
#print('last layer output shape: ', last_layer.output_shape)
last_output = last_layer.output
# Flatten the output layer to 1 dimension
x = tf.keras.layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = tf.keras.layers.Dense(512, activation='relu')(x)
x = tf.keras.layers.Dense(256, activation='relu')(x)
# Add a dropout rate of 0.2
x = tf.keras.layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = tf.keras.layers.Dense(4, activation='softmax')(x)
model = Model(pre_trained_model.input, x)
model.compile(optimizer = RMSprop(lr=0.0001), loss = 'categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(train_generator,validation_data = validation_generator,steps_per_epoch = 20,epochs = 20,validation_steps = 25,verbose = 2)
model.save("dcho.rp5")
___________________
import numpy as np
import cv2
import glob
from keras.preprocessing import image
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
labels= ["cat","dog","human","other"]
path='C:/Users/sethr/education/Healthcare/imagedetect/images/*.jpg'
for fim in glob.glob(path):
# predicting images
img=image.load_img(fim, target_size=(150, 150))
x=image.img_to_array(img)
x=np.expand_dims(x, axis=0)
images = np.vstack([x])
plt.figure()
plt.imshow(img)
plt.show()
classes = model.predict(images,batch_size=10)
________________________________________________________
_______________________________________________________
# All images will be rescaled by 1./255.
train_datagen = ImageDataGenerator( rescale = 1.0/255. )
test_datagen = ImageDataGenerator( rescale = 1.0/255. )
# --------------------
# Flow training images in batches of 20 using train_datagen generator
# --------------------
train_generator = train_datagen.flow_from_directory(train_dir,
batch_size=20,
shuffle='True',
class_mode='categorical',
target_size=(150, 150))
# --------------------
# Flow validation images in batches of 20 using test_datagen generator
# --------------------
validation_generator = test_datagen.flow_from_directory(validation_dir,
target_size = (150, 150),
batch_size=20,
class_mode='categorical',
shuffle='True',
)
_______________________________________________________________
The problem is it is returning always human as prediction.. I played around with Adam, Adjusted learning rate but still the prediction remains the same. Any insight.
The issue is you have not done the rescaling part when you predicting images.
You are doing rescaling only for training and validation
train_datagen = ImageDataGenerator( rescale = 1.0/255. )
test_datagen = ImageDataGenerator( rescale = 1.0/255. )
# Note - this test_datagen used for validation
In order to get correct predictions, we should do the same preprocessing steps as we did for training and validation. So you need to rescale the image.
You can rescale the image by using this code
x = x* 1.0/255.0
So the correct predicting image part is shown below.
for fim in glob.glob(path):
# predicting images
img=image.load_img(fim, target_size=(150, 150))
x=image.img_to_array(img)
x=np.expand_dims(x, axis=0)
# Add this line
x = x* 1.0/255.0
images = np.vstack([x])
plt.figure()
plt.imshow(img)
plt.show()
classes = model.predict(images,batch_size=10)

I am running out of 25gb ram on google colab

This is my code below I am making a multilabel classification model using 8000 x-ray images can someone here help me this is my code below most of the ram is used while loading the images itself and only 10 epochs are able to run.
Can someone tell me what changes do I need to make to this code for it to run and generate the model.
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import VGG16
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.layers import *
from tensorflow.keras.layers import AveragePooling2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import cv2
import os
# construct the argument parser and parse the arguments
# initialize the initial learning rate, number of epochs to train for,
# and batch size
INIT_LR = 1e-3
EPOCHS = 40
BS = 66
# grab the list of images in our dataset directory, then initialize
# the list of data (i.e., images) and class images
print("[INFO] loading images...")
imagePaths = list(paths.list_images('/content/drive/My Drive/testset/'))
data = []
labels = []
# loop over the image paths
for imagePath in imagePaths:
# extract the class label from the filename
label = imagePath.split(os.path.sep)[-2]
# load the image, swap color channels, and resize it to be a fixed
# 224x224 pixels while ignoring aspect ratio
image = cv2.imread(imagePath)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
# update the data and labels lists, respectively
data.append(image)
labels.append(label)
# convert the data and labels to NumPy arrays while scaling the pixel
# intensities to the range [0, 255]
data = np.array(data) / 255.0
labels = np.array(labels)
# perform one-hot encoding on the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
# partition the data into training and testing splits using 80% of
# the data for training and the remaining 20% for testing
(trainX, testX, trainY, testY) = train_test_split(data, labels,
test_size=0.20, stratify=labels, random_state=42)
# initialize the training data augmentation object
trainAug = ImageDataGenerator(
rotation_range=15,
fill_mode="nearest")
# load the VGG16 network, ensuring the head FC layer sets are left
# off
baseModel = VGG16(weights="imagenet", include_top=False,
input_tensor=Input(shape=(224, 224, 3)))
# construct the head of the model that will be placed on top of the
# the base model
headModel = baseModel.output
headModel = AveragePooling2D(pool_size=(4, 4))(headModel)
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(64, activation="relu")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(3, activation="softmax")(headModel)
# place the head FC model on top of the base model (this will become
# the actual model we will train)
model = Model(inputs=baseModel.input, outputs=headModel)
# loop over all layers in the base model and freeze them so they will
# *not* be updated during the first training process
for layer in baseModel.layers:
layer.trainable = False
# compile our model
print("[INFO] compiling model...")
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
# train the head of the network
print("[INFO] training head...")
H = model.fit(
trainAug.flow(trainX, trainY, batch_size=BS),
steps_per_epoch=len(trainX) // BS,
validation_data=(testX, testY),
validation_steps=len(testX) // BS,
epochs=EPOCHS)
# make predictions on the testing set
print("[INFO] evaluating network...")
predIdxs = model.predict(testX, batch_size=BS)
# for each image in the testing set we need to find the index of the
# label with corresponding largest predicted probability
predIdxs = np.argmax(predIdxs, axis=1)
# show a nicely formatted classification report
print(classification_report(testY.argmax(axis=1), predIdxs,
target_names=lb.classes_))
# compute the confusion matrix and and use it to derive the raw
# accuracy, sensitivity, and specificity
cm = confusion_matrix(testY.argmax(axis=1), predIdxs)
total = sum(sum(cm))
acc = (cm[0, 0] + cm[1, 1]) / total
sensitivity = cm[0, 0] / (cm[0, 0] + cm[0, 1])
specificity = cm[1, 1] / (cm[1, 0] + cm[1, 1])
# show the confusion matrix, accuracy, sensitivity, and specificity
print(cm)
print("acc: {:.4f}".format(acc))
print("sensitivity: {:.4f}".format(sensitivity))
print("specificity: {:.4f}".format(specificity))
# plot the training loss and accuracy
N = EPOCHS
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc",color='green')
plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc")
plt.title("Training Loss and Accuracy on COVID-19 Dataset")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig('/content/drive/My Drive/setcovid/plot2.png')
# serialize the model to disk
print("[INFO] saving COVID-19 detector model...")
model.save('/content/drive/My Drive/setcovid/model2',save_format="h5" )
You can try to generate TFRecords from this data, store them into your drive and then feed them into your model through batches instead of directly loading them to memory. I would recommend the Hvass Laboratories YouTube channel, tensorflow tutorials playlist, tutorial number 18, TFRecords and Dataset API and the Dataset api tensorflow's official documentation.