Scott Kim
Scott Kim

Reputation: 243

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None

Hello this is my code for Implementing CNN with Keras backend with tensor flow, for classifying image I don't know what part i am doing wrong.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

img_width, img_height = 224, 224

train_data_dir = '/Users/CK/data/train'
validation_data_dir = '/Users/CK/data/validation'

nb_train_samples = 47000
nb_validation_samples = 47000
epochs = 50
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(12,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy', optimizer = 'adam', metrics=['accuracy'])

train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True
        )

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height),
                                                    batch_size=batch_size, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,target_size=(img_width, img_height),
                                                        batch_size=batch_size, class_mode='categorical')

model.fit_generator(train_generator,
                    steps_per_epoch=nb_train_samples// batch_size, epochs=epochs,
                    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

But then I got an error

runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')
Found 46827 images belonging to 9 classes.
Found 46827 images belonging to 9 classes.
Epoch 1/50
Exception in thread Thread-7:
Traceback (most recent call last):
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 612, in data_generator_task
    generator_output = next(self._generator)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 727, in __next__
    return self.next(*args, **kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 960, in next
    target_size=self.target_size)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 318, in load_img
    raise ImportError('Could not import PIL.Image. '
ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL.

Traceback (most recent call last):

  File "<ipython-input-13-15de1a62b9cf>", line 1, in <module>
    runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/CK/Desktop/test.py", line 66, in <module>
    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/models.py", line 1110, in fit_generator
    initial_epoch=initial_epoch)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 1865, in fit_generator
    str(generator_output))

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None

How do i fix problem? I appreciate if you guys help to fix the code with details. thx

Upvotes: 0

Views: 2917

Answers (2)

sefa
sefa

Reputation: 1

You must make file into train_data_dir,validation_data_dir and next you must carry images into this file.

Upvotes: 0

Rahul
Rahul

Reputation: 2100

There are two errors here

  1. ImportError for PIL

  2. ValueError

and I think your second one is depended on the first. Why?

because the image data got corrupted as it might be none because of the absence of required library and making validation with this data might be causing the generator to return weird values.

To resolve first you will need to install PIL by the following command

  # sudo does not require if you are using virtualenv
  $ sudo pip install Pillow 

Hopefully, your second issue will also get resolved.

Upvotes: 1

Related Questions