ValueError: Error when checking target: expected dense_2 to have shape (None, 2) but got array with shape (321, 3)

I want to create an image classifier using keras, and train it with a few example images. Then, i will be using pre-trained models and adding a few layers at the end, but first, i want to understand keras and CNNs.

My console prints the following error:

ValueError: Error when checking target: expected dense_2 to have shape (None, 2) but got array with shape (321, 3)

Here is my code:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import time

import numpy as np
import cv2
import time
from PIL import Image

import keras
import glob
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer


labels = ['buena', 'mala', 'otro']

def to_one_hot(labels, ys):
    result = np.zeros((len(ys),len(labels)))
    for i in range(result.shape[0]):
        for j in range(result.shape[1]):
            result[i,j] = int(ys[i] == labels[j])
    return result

def build_dataset(labels):
    num_classes = len(labels)
    x = []
    y = []
    for label in labels:
        for filename in (glob.glob('./tf_files/papas_fotos/'+label+'/*.jpg')):
            img = cv2.imread(filename)
            img = np.resize(img,(100,100, 3))
            x.append(img)
            y.append(label)
    y = to_one_hot(labels, y)
    # y = keras.utils.to_categorical(y, num_classes=3)
    x = np.array(x)
    x_train = x[20:]
    y_train = y[20:]
    x_test = x[:19]
    y_test = y[:19]
    print (x.shape, y.shape)
    return x_train, y_train, x_test, y_test

model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

x_train, y_train, x_test, y_test = build_dataset(labels)

model = load_model('thebestmodel.h5')
print (model)
model.fit(x_train, y_train, batch_size=32, epochs=20)
score = model.evaluate(x_test, y_test, batch_size=32)
model.save('thebestmodel.h5')
print (score)

What mistake am I making? I think that may be the size of my one hot encoded labels, but i can't make it work.

Thanks!

Upvotes: 0

Views: 193

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Although your code was fixed for this specific error, you're loading a saved model: model = load_model('thebestmodel.h5')

This is undoing everything before this line.

Upvotes: 1

Related Questions