0

I am currently trying to build my CNN for face detection using tensorflow.keras in python. It's supposed to take two types of images: Face and Nonface. The model that I'm trying to implement is from a table [Cnn][1], but i keep getting errors and even if i fix one i get another one and I got stuck in a circle of errors. [1]: https://i.stack.imgur.com/WJCPb.png Please tell me what can i try to fix it?

testRatio = 0.2
valRatio = 0.2
path="D:\ObjectsRecognition\data"
folder=["face","nonface"]
class_names = ["Face","Nonface"]
predictionList = []


def label(numpy):
    npList=np.array([])
    for i in range(len(numpy)):
        if numpy[i]=="face":
            npList=np.append(npList,[0])
        else:
            npList=np.append(npList,[1])
    return npList

def file():

    ############################

    images = []  # LIST CONTAINING ALL THE IMAGES
    classNo = []  # LIST CONTAINING ALL THE CORRESPONDING CLASS ID OF IMAGES
    myList = os.listdir(path)
    print("Total Classes Detected:", len(myList))
    noOfClasses = len(myList)
    print("Importing Classes .......")
    for x in folder:
        myPicList = os.listdir(path + "/" + x)
        for y in myPicList:
            curImg = cv.imread(path + "/" + x + "/" + y)
            curImg = cv.resize(curImg, (231, 231))
            images.append(curImg)
            classNo.append(x)

        print(x, end=" ")

    print(" ")

    print("Total Images in Images List = ", len(images))
    print("Total IDS in classNo List= ", len(classNo))
    #######################
    #### CONVERT TO NUMPY ARRAY
    images = np.array(images)
    classNo = np.array(classNo)


    #### SPLITTING THE DATA
    X_train, X_test, y_train, y_test = train_test_split(images, classNo, test_size=testRatio)
    print(len(X_train) )
    print(len(X_test) )
    print(len(y_train) )
    print(len(y_test) )

    ####################
    (training_images, training_labels), (testing_images, testing_labels) = (X_train,label(y_train)), (X_test,label(y_test))
    training_images, testing_images = training_images/255, testing_images/255
    return (training_images, training_labels), (testing_images, testing_labels)



def defineTrainModel():
    model = models.Sequential()

    model.add(layers.Conv2D(96, (11, 11),strides=(4,4) ,activation='relu', input_shape=(231, 231, 3)))
    model.add(layers.MaxPooling2D((2, 2),strides=(2,2)))

    model.add(layers.Conv2D(256, (5, 5),strides=(1,1), activation='relu',input_shape=(24, 24, 3)))
    model.add(layers.MaxPooling2D((2, 2),strides=(2,2)))

    model.add(layers.Conv2D(512, (3, 3), strides=(1,1) ,activation='relu',input_shape=(12, 12, 3)))
    model.add(layers.ZeroPadding2D(padding=(1,1)))


    model.add(layers.Conv2D(1024, (3, 3), strides=(1, 1), activation='relu', input_shape=(12, 12, 3)))
    model.add(layers.ZeroPadding2D(padding=(1,1)))


    model.add(layers.Conv2D(1024, (3, 3), strides=(1, 1), activation='relu', input_shape=(24, 24, 3)))
    model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
    model.add(layers.ZeroPadding2D(padding=(1,1)))
    model.add(layers.Flatten())

    model.add(layers.Dense(3072, activation='relu',input_shape=(6,6,3)))
    model.add(layers.Dense(4096, activation='relu',input_shape=(1,1,3)))
    model.add(layers.Dense(2, activation='softmax',input_shape=(1,1,3)))


    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    model.summary()
    model.fit(training_images, training_labels, epochs=30, validation_data=(testing_images, testing_labels))

    loss, accuracy = model.evaluate(testing_images, testing_labels)
    print(f"Loss: {loss}")
    print(f"Accuracy: {accuracy}")

    model.save("FancyGPUTrainedModel.h5")

(training_images, training_labels), (testing_images, testing_labels)= file()   #Spliting the data
defineTrainModel()

This is the error that i am getting, but if i try to fix it i get another one: ValueError: Input 0 of layer zero_padding2d is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: (None, 51200)

This is the model summary: Model: "sequential"


Layer (type) Output Shape Param #

conv2d (Conv2D) (None, 59, 59, 96) 34944


max_pooling2d (MaxPooling2D) (None, 29, 29, 96) 0


conv2d_1 (Conv2D) (None, 25, 25, 256) 614656


max_pooling2d_1 (MaxPooling2 (None, 12, 12, 256) 0


conv2d_2 (Conv2D) (None, 10, 10, 512) 1180160


zero_padding2d (ZeroPadding2 (None, 12, 12, 512) 0


conv2d_3 (Conv2D) (None, 10, 10, 1024) 4719616


zero_padding2d_1 (ZeroPaddin (None, 12, 12, 1024) 0


conv2d_4 (Conv2D) (None, 10, 10, 1024) 9438208


max_pooling2d_2 (MaxPooling2 (None, 5, 5, 1024) 0


zero_padding2d_2 (ZeroPaddin (None, 7, 7, 1024) 0


dense (Dense) (None, 7, 7, 3072) 3148800


dense_1 (Dense) (None, 7, 7, 4096) 12587008


dense_2 (Dense) (None, 7, 7, 2) 8194

Total params: 31,731,586 Trainable params: 31,731,586 Non-trainable params: 0


And Training labels: shape (6607,)

Testing labels: shape: (1652,)

Training Images: shape (6607, 245, 245, 3)

Testing Images: shape: (1652, 245, 245, 3)

  • 1
    Well the problem is that it makes no sense to use ZeroPadding2D after doing Flatten, because ZeroPadding2D expects an image as inputs (4 dimensions), while Flatten transforms the data into 2 dimensions. So you get an error. – Dr. Snoopy Apr 21 '21 at 18:52
  • @Dr.Snoopy Thanks, that solved one issue. Now when te model is trying to train, I get tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [1568,2] and labels shape [32] [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at /ObjectsRecognition/NewData/ObjectDetection.py: 127) ]] [Op:__inference_train_function_1361] – Dicsok Gabriel Apr 21 '21 at 20:23
  • According to the error, the number training labels and predictions don't match. Could you print model.summary() and shape of training labels? – Uchiha012 Apr 22 '21 at 07:49
  • @Uchiha012 I printed the model summary and the shape of labels and images that i am using for training and testing – Dicsok Gabriel Apr 22 '21 at 12:09
  • @DicsokGabriel Thanks for updating. Add layer.Flatten() after the last zero padding. Currently your output is in (None, 7, 7, 2) shape and it should be (None, 2) as in the end you want the probabilities of the classes which in this case is 2. – Uchiha012 Apr 22 '21 at 14:27
  • @Uchiha012 Thanks, that seemed to solve that problem, but now i get another error tensorflow.python.framework.errors_impl.NotFoundError: No algorithm worked! – Dicsok Gabriel Apr 22 '21 at 17:49
  • Just to be sure, did you remove the input_shape parameter from the last three dense layers? – Uchiha012 Apr 23 '21 at 11:44
  • @Uchiha012 No, I didn't remove it. I updated the code from this post now with the modifications that i made. – Dicsok Gabriel Apr 23 '21 at 13:50
  • I apologize for being unclear, but you must remove the input_shape parameter from the last three dense layers. – Uchiha012 Apr 23 '21 at 15:27
  • @Uchiha012 I removed the input_shape from the last three dense layers but i still get the same error. – Dicsok Gabriel Apr 23 '21 at 16:19
  • Try the first solution in this question: https://stackoverflow.com/questions/59340465/how-to-solve-no-algorithm-worked-keras-error – Uchiha012 Apr 24 '21 at 12:11
  • @Uchiha012 Well that fixed everything. Thank you verry much. How do I mark your comments as the right answer?:)) – Dicsok Gabriel Apr 24 '21 at 16:30
  • I'll just combine them into an answer, then go ahead mark and upvote. ;) – Uchiha012 Apr 24 '21 at 19:10
  • Ok, sounds good. – Dicsok Gabriel Apr 24 '21 at 19:15

1 Answers1

0

tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [1568,2] and labels shape [32]

The above error can be solved by adding a layer.Flatten() after the last zero padding as currently the output is in (None, 7, 7, 2) shape and it should be (None, 2) as in the end you want the probabilities of the classes which in this case is 2.

tensorflow.python.framework.errors_impl.NotFoundError: No algorithm worked!

Refer the solution provided by Oktay Alizada in the question: How to solve "No Algorithm Worked" Keras Error?

Uchiha012
  • 821
  • 5
  • 9