Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

python - ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (117, 1, 32, 32, 3)

I was developing a image classification project when i got this error for fitting my model.

ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (117, 1, 32, 32, 3)

This is my code for training the dataset. It has 3 features and 117 images.

def create_train_dataset():
x_train = []
y_train = []
for foldername in os.listdir(train_data):
    label = map[foldername]
    for image1 in os.listdir(train_data + "/" + foldername):
        img = image.load_img(train_data + "/" + foldername + "/" + image1, target_size=(32, 32))
        img = image.img_to_array(img)
        img = np.expand_dims(img, axis=0)
        x_train.append(img)
        y_train.append(label)
x_train = np.array(x_train)
x_train = x_train.astype('float32')/255.0
y_train = np_utils.to_categorical(y_train)
print("Training Dataset Created")
return x_train, y_train

I thought it would have 4 dimensions but output of its shape gave :

Training Data Shape =  (117, 1, 32, 32, 3)

And so after running model fit line :

model = Sequential()
model.add(Conv2D(filters=5, kernel_size=5, padding='same', activation='relu', input_shape=(32, 32, 3)))

I got the stated error. I thought the x_train would have 4 dimensions but somehow it has 5 which gives error. Can anyone please tell why it happens and how i can correct it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is because of np.expand_dims(img, axis=0).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...