# Why my Keras CNN model isn't learning

My project have to decide if a image is 'pdr' or 'nonPdr', and I have 391 images (22 of PDR class, and the 369 of nonPdr)..

In my first model i was trying this: https://stackoverflow.com/questions/57663233/my-keras-cnn-return-the-same-output-value-how-can-i-fix-improve-my-code .. and my return was always the same...

Now I made some changes in my model file:

TRAIN_DIR = 'train_data/'
#TEST_DIR = 'test_data/'

def ReadImages(Path):
LabelList = list()
ImageCV = list()

# Get all subdirectories
FolderList = os.listdir(Path)

# Loop over each directory
for File in FolderList:
if(os.path.isdir(os.path.join(Path, File))):
for Image in os.listdir(os.path.join(Path, File)):
# Convert the path into a file
ImageCV.append(cv2.imread(os.path.join(Path, File) + os.path.sep + Image))
# Add a label for each image and remove the file extension
classes = ["nonPdr", "pdr"]
LabelList.append(classes.index(os.path.splitext(File)[0]))
else:
ImageCV.append(cv2.imread(os.path.join(Path, File) + os.path.sep + Image))
# Add a label for each image and remove the file extension
classes = ["nonPdr", "pdr"]
LabelList.append(classes.index(os.path.splitext(File)[0]))

return ImageCV, LabelList

model = Sequential()
model.add(Conv2D(64, kernel_size=(3,3), padding="same",activation="relu", input_shape=(605,700,3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128,  kernel_size=(4,4), padding="same",activation="relu"))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(2, activation='sigmoid'))
model.compile(optimizer='RMSprop', loss='binary_crossentropy', metrics=['accuracy'])

data, labels = ReadImages(TRAIN_DIR)

data = np.array(data, dtype="float") / 255.0

le = LabelEncoder()
labels = le.fit_transform(labels)
labels = np_utils.to_categorical(labels, 2)

model.fit(data, labels, epochs=8, batch_size=20)

model.save('model.h5')


... but running this code give me a Loss = 8.0 and a acc = 0.50

What can I do? I appreciate any answer..

UPDATE I forgot that I reduce my train imgs to 20/20

## 1 Answer

It seems that you have an output size of 2 in your final layer, while you should rather have size 1 (because of your sigmoid output and binary cross entropy loss).

Also, don’t use the to_categorical transformation as you only have two classes so no need to one-hot encode.

Try to change this and see if training improves.

• ValueError: Error when checking target: expected dense_1 to have shape (1,) but got array with shape (2,) I have two classes.. – 0nroth1 Aug 30 '19 at 18:37
• I’ve edited the answer, don’t use to_categorical – Elliot Aug 30 '19 at 18:41
• I had the same output.. please see my update, i reduce to 20 pdr and 20 nonpdr images in my train data.. – 0nroth1 Aug 30 '19 at 18:47
• @Gilberto yep, but still it should not change the issue. However this is very little data and a CNN would hardly work. – Elliot Aug 30 '19 at 18:49
• so what can i do? – 0nroth1 Aug 30 '19 at 18:51