10dan
10dan

Reputation: 1

Why does my Conv2D model compain it's not getting 4 dimensions when the shape of my input data is 4D?

I am trying to classify the MNIST database of handwritten digits in a convolution network but have been getting this error: ValueError: Error when checking input: expected conv2d_40_input to have 4 dimensions, but got array with shape (28, 28, 1)

My task is to use cross sampling, that is why the data is being split into 5 groups.

def train_conv_subsample():

#splitting data into chunks
chunks = []
chunk_labels = []
num_chunks = 5
chunk_size = int(train_data.shape[0]/num_chunks)
for i in range(num_chunks):
    chunks.append(train_data[(i*chunk_size):(i+1)*chunk_size])
    chunk_labels.append(train_labels[(i*chunk_size):(i+1)*chunk_size])

#Create another convolutional model to train.
for i in range(num_chunks):
    current_train_data = []
    current_train_lables = []
    for j in range(num_chunks):
        if(i == j):
            validation_data = chunks[i]
            validation_labels = chunk_labels[i]
        else:
            current_train_data.extend(chunks[j])
            current_train_lables.extend(chunks[j])

    print(np.shape(current_train_data)) #Says it has a shape of (48000,28,28, 1)

    model = models.Sequential([
        layers.Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=(28,28,1)),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Flatten(),
        layers.Dense(32, activation='relu'),
        layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.CategoricalCrossentropy(),
                  metrics=['accuracy'])

    #But when it goes to fit it raises the error: expected 4 dim, but got array with shape (28, 28, 1)
    model.fit(current_train_data, current_train_lables, epochs=1, validation_data=(validation_data, validation_labels))
    tf.keras.backend.clear_session()

That is my code, and the dataset im using can be imported from keras datasets, datasets.mnist.load_data()

Thanks for any help

Upvotes: 0

Views: 342

Answers (1)

xxzozoxx1
xxzozoxx1

Reputation: 82

I think the problem is that with the shape of the image in the mnist dataset you need to reshape them to 4 dim arrays using the reshape in the numpy array library as follows :

    import numpy as np 

    np.reshape(dataset,(-1,28,28,1) 

if this did not work try to convert them to grayscale before reshaping using OpenCV library

Upvotes: 1

Related Questions