Reputation: 63
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)
Upvotes: 1
Views: 333
Reputation: 86600
Convolutions use 4 dimensions. Considering you're using "channels_first":
Your input is missing the channels.
t = np.random.rand(20000,1,250,50)
Upvotes: 1