1

I'm trying to train a CNN on word vectors generated using the gensim library. After I have generated all of my data in numeric form, I try to pass it on to a CNN model using Keras when I get the following error:

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

I've searched on this problem for hours, and all of the solutions posted for similar/same issues haven't been able to solve this error for me. Can anyone see where I'm going wrong with the input dimensions? I've generated some random numpy data that recreates the error:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Convolution2D, Flatten, Dropout
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras.callbacks import TensorBoard

t = np.random.rand(20000,250,50)
l = np.random.rand(20000,1)

embedding_vecor_length = 50
net = Sequential()
net.add(Convolution2D(64, 3,input_shape=(1,250,50), 
data_format='channels_first'))
# Convolutional model (3x conv, flatten, 2x dense)
net.add(Convolution2D(32,(3), padding='same'))
net.add(Convolution2D(16,(3), padding='same'))
net.add(Convolution2D(8,(3), padding='same'))
net.add(Flatten())
net.add(Dropout(0.2))
net.add(Dense(180,activation='sigmoid'))
net.add(Dropout(0.2))
net.add(Dense(1,activation='sigmoid'))
net.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

tensorBoardCallback = TensorBoard(log_dir='./logs', write_graph=True)
net.summary()

net.fit(t, l, epochs=3, callbacks=[tensorBoardCallback], batch_size=64)

1 Answer 1

1

Convolutions use 4 dimensions. Considering you're using "channels_first":

  • Images
  • Channels
  • Side 1
  • Side 2

Your input is missing the channels.

t = np.random.rand(20000,1,250,50)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick response! I'm not sure how I should add the channels to the shape of my array. Right now the shape of my data is (20000,250,50), so I would I add the channel dimension to the numpy array?
array = array.reshape((20000,1,250,50))
I suggest to use the channels last, as usual in Keras. Then array = array.reshape((20000,250,50,1))
Right on. Thanks that did the trick. Now I have another issue(nested np arrays) but is unrelated to this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.