0

I having trouble in here:

About the code: I create a model here. The first step is to initialize the model with Sequential(). After that, we flatten our data and add our additional 3 (or more) hidden layers.

import pandas as pd
import numpy as np 
import itertools
import keras
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img 
from keras.models import Sequential 
from keras import optimizers
from keras.preprocessing import image
from keras.layers import Dropout, Flatten, Dense 
from keras import applications 
from keras.utils.np_utils import to_categorical 
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg
%matplotlib inline
import math 
import datetime
import time

import tensorflow as tf 

img_width, img_height = 224, 224 
 
#Create a bottleneck file
top_model_weights_path = 'model_.h5'

train_data_dir = 'data/train' 
#validation_data_dir = ‘data/validation’ 
test_data_dir = 'data/test'

epochs = 7 #this has been changed after multiple model run 
# batch size used by flow_from_directory and predict_generator 
batch_size = 50 

VGG16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255) 

start = datetime.datetime.now()
 
generator = datagen.flow_from_directory( 
    train_data_dir, 
    target_size=(img_width, img_height), 
    batch_size=batch_size, 
    class_mode=None, 
    shuffle=False) 

nb_train_samples = len(generator.filenames) 
num_classes = len(generator.class_indices) 
 
predict_size_train = int(math.ceil(nb_train_samples / batch_size)) 
 
bottleneck_features_train = VGG16.predict_generator(generator, predict_size_train) 
 
np.save('bottleneck_features_train.npy', bottleneck_features_train)
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)

generator_top = datagen.flow_from_directory( 
   train_data_dir, 
   target_size=(img_width, img_height), 
   batch_size=batch_size, 
   class_mode='categorical', 
   shuffle=False) 
 
nb_train_samples = len(generator_top.filenames) 
num_classes = len(generator_top.class_indices) 
 
# load the bottleneck features saved earlier 
train_data = np.load('bottleneck_features_train.npy') 
 
# get the class labels for the training data, in the original order 
train_labels = generator_top.classes 
 
# convert the training labels to categorical vectors 
train_labels = to_categorical(train_labels, num_classes=num_classes)

start = datetime.datetime.now()
model = Sequential() 
model.add(Flatten(input_shape=train_data.shape[1:])) 
model.add(Dense(100, activation=keras.layers.LeakyReLU(alpha=0.3))) 
model.add(Dropout(0.5)) 
model.add(Dense(50, activation=keras.layers.LeakyReLU(alpha=0.3))) 
model.add(Dropout(0.3)) 
model.add(Dense(num_classes, activation='softmax'))


model.compile(loss='categorical_crossentropy',
   optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
   metrics=['acc'])


history = model.fit(train_data, train_labels, 
   epochs=7,
   batch_size=batch_size, 
   validation_data=(validation_data, validation_labels))


model.save_weights(top_model_weights_path)

(eval_loss, eval_accuracy) = model.evaluate( 
    validation_data, validation_labels, batch_size=batch_size, verbose=1)

print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100)) 
print("[INFO] Loss: {}".format(eval_loss)) 
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)

My error is :

ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>

How I can fix this: I need to know how to fix this error. I was tried but still could not fix it.

Dropzz
  • 19
  • 5
  • in which line of code? – User Aug 30 '21 at 13:52
  • `---> 17 history = model.fit(train_data, train_labels, ` this is the line – Dropzz Aug 30 '21 at 14:07
  • can you post the whole code? `train_data`, `train_labels`, ... can't see them. – User Aug 31 '21 at 05:58
  • Added full code @User – Dropzz Aug 31 '21 at 06:33
  • Have you checked that both validation and train data/labels are not `None`? – User Aug 31 '21 at 10:12
  • `train_data = None` and `train_labels = None` like this right – Dropzz Aug 31 '21 at 14:22
  • try to put this code at line 16: `if train_data is None or train_labels is None or validation_data is None or validation_labels is None: exit(-1)`. If the program stops then something is None. Or you can just put a breakpoint and check the values of those variables. – User Sep 01 '21 at 05:55
  • I did like that, But, Same error – Dropzz Sep 01 '21 at 17:22
  • Try to print those 4 variables and check if they are not `None`, because if the the error is at the line 17, which is the `fit()` line, only those variables could be the problem, in my opinion. – User Sep 02 '21 at 06:04
  • I set `validation_data = not None` and `validation_labels = not None` those.. Now this error will appear `IndexError: list index out of range` – Dropzz Sep 03 '21 at 05:54
  • Found similar type of issue answered, if [this](https://stackoverflow.com/questions/57874436/tensorflow-data-adapter-error-valueerror-failed-to-find-data-adapter-that-can) can help to resolve your issue? –  Sep 30 '21 at 14:54
  • @TFer2 I added an answer. Please check that. It is working for me. check for yours. – Dropzz Oct 04 '21 at 03:41

1 Answers1

0

I did like this. This is working properly. Pls try to do this.

import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.metrics import confusion_matrix
import itertools
import os, glob
from tqdm import tqdm
from efficientnet.tfkeras import EfficientNetB4

img_path = '.\\Data\\test\\PNEUMONIA\\PNEUMONIA.jpg'

model_path = '.\\model.h5'

# labels used while training
labels = {0: 'NORMAL', 1: 'PNEUMONIA', 2: 'COVID'}

# loading the model
model = tf.keras.models.load_model(model_path, compile=False)

# model allowable image dimensions
img_width, img_height = 224, 224
# loading the image
image = cv2.imread(img_path)
# resizing the image
image = cv2.resize(image, (img_width, img_height))
# coverting BGR to RGB format
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# adding a new axis [batch axis]
image = image[np.newaxis, ...]
# rescale image from [0,255] to [0,1]
image = image / 255.
# predicting the output
prediction = model.predict(image)
# squeeze/remove an extra axis
prediction = np.squeeze(prediction)

for i in labels:
    print(labels[i], ':', prediction[i])

# picking the class with max. score
prediction = np.argmax(prediction)
# selecting the class with max. score
output = labels[prediction]
#print('Prediction:',output)
print()
print('The image which you entered, prediction is:',output)
Dropzz
  • 19
  • 5