简体   繁体   中英

getting error while predicting a test image - cannot reshape array of size

I am trying to do Image Recognition in Python with TensorFlow and Keras and I have followed below blog for the same. https://stackabuse.com/image-recognition-in-python-with-tensorflow-and-keras/

I need to find the output of each layer and at the same time I am also trying to predict an image.

Please see my code below. I am not able to predict and image that I am providing Any help and inputs here to get this fixed is much appreciated.

    import numpy
    from keras import models
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Flatten, BatchNormalization, Activation
    from keras.layers.convolutional import Conv2D, MaxPooling2D
    from keras.constraints import maxnorm
    from keras.utils import np_utils
    from matplotlib import pyplot


    # Create dictionary of target classes
    label_dict = {
     0: 'T-shirt/top',
     1: 'Trouser',
     2: 'Pullover',
     3: 'Dress',
     4: 'Coat',
     5: 'Sandal',
     6: 'Shirt',
     7: 'Sneaker',
     8: 'Bag',
     9: 'Ankle boot',
    }

    # example of loading the mnist dataset
    from keras.datasets import fashion_mnist
    from matplotlib import pyplot
    # load dataset
    #trainX, trainy), (testX, testy) = fashion_mnist.load_data()
    (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
    # summarize loaded dataset
    print('Train: X=%s, y=%s' % (X_train.shape, y_train.shape))
    print('Test: X=%s, y=%s' % (X_test.shape, y_test.shape))
    # plot first few images
    for i in range(9):
        # define subplot
        pyplot.subplot(330 + 1 + i)
        # plot raw pixel data
        pyplot.imshow(X_train[i], cmap=pyplot.get_cmap('gray'))
        # show the figure
    
    pyplot.show()


    # normalize the inputs from 0-255 to between 0 and 1 by dividing by 255
        
    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')
    X_train = X_train / 255.0
    X_test = X_test / 255.0


    # one hot encode outputs
    y_train = np_utils.to_categorical(y_train)
    y_test = np_utils.to_categorical(y_test)
    class_num =10

    numpy.max(X_train[0])

    numpy.min(X_train[0])

    X_train[0][500:]
    
    y_train[:500][0]
    
    y_train[:500][0]

    X_train.shape, X_test.shape
    
    y_train.shape, y_test.shape
    
    # Reshape training and testing image
    X_train = X_train.reshape(-1, 28, 28, 1)
    X_test = X_test.reshape(-1,28,28,1)
    
    model = Sequential()
    
    model.add(Conv2D(32, (3, 3), input_shape=X_train.shape[1:], padding='same'))
    model.add(Activation('relu'))
    
    model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same'))
    
    model.add(Dropout(0.2))
    
    model.add(BatchNormalization())
    
    model.add(Conv2D(64, (3, 3), padding='same', name='test1'))
    model.add(Activation('relu'))
    
    
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(BatchNormalization())
    
    
    
    model.add(Conv2D(64, (3, 3), padding='same', name='test2'))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), padding='same', name='test3'))
    model.add(Activation('relu'))
    model.add(Dropout(0.2))
    model.add(BatchNormalization())
    
    
    model.add(Flatten())
    model.add(Dropout(0.2))
    
    model.add(Dense(256, kernel_constraint=maxnorm(3)))
    model.add(Activation('relu'))
    model.add(Dropout(0.2))
    model.add(BatchNormalization())
    model.add(Dense(128, kernel_constraint=maxnorm(3)))
    model.add(Activation('relu'))
    model.add(Dropout(0.2))
    model.add(BatchNormalization())
    
    
    
    model.add(Dense(class_num))
    model.add(Activation('softmax'))
    
    
    
    epochs = 2
    optimizer = 'adam'
    
    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])


    print(model.summary())


    model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=64)


    # Model evaluation
    scores = model.evaluate(X_test, y_test, verbose=0)
    print("Accuracy: %.2f%%" % (scores[1]*100))


# This I am predicting from test images
    image_index = 430
    pyplot.imshow(X_test[image_index].reshape(28, 28,1),cmap='Greys')
    pred = model.predict(X_test[image_index].reshape(-1, 28, 28, 1))
    print(pred.argmax())

I am trying to predict model using image below

在此处输入图像描述

Trying to predict this image using the above trained model

在此处输入图像描述

I have written below code

from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator

    img_path = 'data/img.jpg'
    img = image.load_img(img_path, target_size=(28, 28))
    img_tensor = image.img_to_array(img)
    img_tensor = numpy.expand_dims(img_tensor, axis=0)
    img_tensor /= 255.
    pyplot.imshow(img_tensor[0])
    pyplot.show()
    print(img_tensor.shape)


    pred = model.predict(img_tensor.reshape(-1, 28, 28, 28))
    print(pred.argmax())

With the above model.predict, I am getting below error

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-125-965f3e01bc73> in <module>
    ----> 1 pred = model.predict(img_tensor.reshape(-1, 28, 28, 28))
          2 print(pred.argmax())

    **ValueError: cannot reshape array of size 2352 into shape (28,28,28)**

I have tried all options but not getting the right results. Can any one help me to get the right results please?

Your input is of size (28,28,3) but you are transforming it into (28,28,28) which is wrong. Try:

pred = model.predict(img_tensor.reshape(-1, 28, 28, 3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM