Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow, expected conv2d_input to have 4 dimensions

I'm using tf.keras and I'm getting following error:

ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (24946, 50, 50)

Could someone help me with it?

Code (Image_Size is: 50x50)

import tensorflow as tf
import numpy as np
import pickle
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D


pickle_ind = open("x.pickle", "rb")
x = pickle.load(pickle_ind)
x = np.array(x, dtype=float)
# x = x/255.0

pickle_ind = open("y.pickle", "rb")
y = pickle.load(pickle_ind)

n_batch = len(x)

model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(50, 50, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))

model.summary()

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.fit(x, y, epochs=20, batch_size=n_batch)
like image 254
007fred Avatar asked May 06 '19 15:05

007fred


1 Answers

Add channels dimension:

x = np.expand_dims(x, -1)

You also need to add output dense layer:

model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(50, 50, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='adam',
              loss='sparse_softmax_crossentropy',
              metrics=['accuracy'])
like image 90
Vlad Avatar answered Nov 04 '22 07:11

Vlad