lejcestlesang
lejcestlesang

Reputation: 75

Error of Shape Using Conv1D in Keras

I have troubles using Conv1D as an input layer in Sequential NN with Keras. Here is my code :

import numpy as np    
from keras.layers.convolutional import Conv1D    
from keras.models import Sequential    
from keras.optimizers import Adam    

conv1d = Conv1D(input_shape=(None, 16), kernel_size=2, filters=2)    

model = Sequential()    
model.add(conv1d)    
model.compile(loss="logcosh", optimizer=Adam(lr=0.001))    

x_train = np.zeros((32, 16, 1))    
y_train = np.zeros((32, 16, 1))    

print(x_train.shape)    

model.fit(x_train, y_train, batch_size=4, epochs=20)     

Here is the error. I have tried multiple things but none of them helped me to resolve the issue.

ValueError: Error when checking input: expected conv1d_47_input to have shape (None, 16) but got array with shape (16, 1)

Upvotes: 2

Views: 6783

Answers (2)

lejcestlesang
lejcestlesang

Reputation: 75

I managed to find a solution using flatten function and a dense layer and it worked

import numpy as np
from keras.layers.convolutional import Conv1D
from keras.models import Sequential
from keras.optimizers import Adam
from keras.layers import Conv1D, Dense, MaxPool1D, Flatten, Input

conv1d = Conv1D(input_shape=(16,1), kernel_size=2, filters=2)

model = Sequential()
model.add(conv1d)
model.add(Flatten())
model.add(Dense(16))

model.compile(optimizer=optimizer,loss="cosine_proximity",metrics=["accuracy"])

x_train = np.zeros((32,16,1))
y_train = np.zeros((32,16))

print(x_train.shape)
print()

model.fit(x_train, y_train, batch_size=4, epochs=20) 

Upvotes: 0

ales_t
ales_t

Reputation: 2017

Conv1D expects the inputs to have the shape (batch_size, steps, input_dim).

Based on the shape of your training data, you have max length 16 and input dimensionality just 1. Is that what you need?

If so, then the input shape can be specified either as (16, 1) (length is always 16) or (None, 1) (dynamic length).

If you meant to define sequences of length 1 and dimensionality 16, then you need a different shape of the training data:

x_train = np.zeros((32, 1, 16))
y_train = np.zeros((32, 1, 16))

Upvotes: 1

Related Questions