Keras BatchNormalization layer incompatibility error - tensorflow

I have the following (part of) network architecture:
Obtained by
...
pool = GlobalAvgPool()(gc_2)
predictions = Dense(units=32, activation='relu', use_bias=False)(pool)
predictions = BatchNormalization()(predictions)
...
I am trying to insert a batch normalization layer, but I get the following error:
ValueError: Input 0 of layer batch_normalization_1 is incompatible with the layer: expected ndim=2, found ndim=3. Full shape received: [None, 1, 32]
I am guessing the second dimension is causing this mishap. Is there any way I can get rid of it?

If your model is complied successfully, there is no problem with your model definition.
This is more likely to happen because of the input data shape and dimensions are incompatible with your model's desired input shape.
expected ndim=2, found ndim=3. means that the model requires a 2D tensor with

Related

Tensorflow Keras output layer shape weird error

I am fairly new to TF, Keras and ML in general.
I am trying to implement a very simple MLP with an input shape of (batch_size,3,2) and an output shape of (batch_size,3), that is (if I got it right): for every 3x2 feature, there is a corresponding 3 value array label.
Here is how I create the model:
model = tf.keras.Sequential([
tf.keras.layers.Dense(50,tf.keras.activations.relu,input_shape=((3,2)),
tf.keras.layers.Dense(3)
])
and these are the X and y shapes:
X_train.shape,y_train.shape
TensorShape([64,3,2]),TensorShape([64,3])
On model.fit I am facing a weird error I cannot understand:
ValueError: Dimensions must be equal, but are 3 and 32 for ... with input shapes: [32,3,3] and [32,3]
I have no clue what's going on, I understand the batch size is 32, but where does that [32,3,3] comes from?
Moreover, if from the original 64, I lower the number (shapes) of X_train and y_train, say, to: (19,3,2) and (19,3), I get the following error instead:
InvalidArgumentError: required broadcastable shapes at loc(unknown)
What's even more weird for me is that if I specify a single unit for the output (last) layer, instead of 3 like this:
model = tf.keras.Sequential([
tf.keras.layers.Dense(50,tf.keras.activations.relu,input_shape=((3,2)),
tf.keras.layers.Dense(1)
])
model.fit works, but the predictions have shape (1,3,1) instead of my expected (3,)
I am very confused.
Whenever you have not any idea about the journey of data throughout your model, use model.summary() to see the details and what happens to the shape of data in each layer.
In this case, the input is a 2D array, and the output is a 1D array, and you just used dense layers. Dense layers can not handle 2d features in nature. For example for an image as input, you can not feed it directly to a dense layer. Instead you should use other layers such as Conv2D or Flatten your input (make it 1D) before feeding your data to the dense layer. Otherwise you will get the other dimension in the output.
Inference: If your input dimension and output dimension differs, somewhere in your model, the shape need to be changed. Most common ways to do so, is using a Flatten layer or GlobalAveragePooling and so on.
When you pass an input to a dense layer, the input should be flattened first. There are 2 ways to deal with this:
Way 1: Adding a flatten input as a first layer of your model:
model = Sequential()
model.add(Flatten(input_shape=(3,2)))
model.add(Dense(50, 'relu'))
model.add(Dense(3))
Way 2: Converting the 2D array to 1D before passing the inputs to your model:
X_train = tf.reshape(X_train, shape=([6]))
or
X_train = tf.reshape(X_train, shape=((6,)))
Then change the input shape of the first layer as:
model.add(Dense(50, 'relu', input_shape=(6,))

Keras: ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis

I am trying to build a neural network using Keras but am getting the error:
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 25168 but received input with shape (None, 34783)
I defined the model to be:
model = Sequential()
model.add(Dense(1024, input_dim = len(X), activation = 'relu'))
model.add(Dense(6, activation='softmax'))
In this, X is the result of using scikit-learn it's CountVectorizer() (after it is trained) as follows:
X = count_vectorizer.transform(X).todense()
Is there any method to fix this? Looking around I found that I might need to reshape the data, however I have no idea how and where.
You are using as input_dim the sample dimensionality: len(X) (the same as X.shape[0]) which is wrong.
Keras expects as input the number of dimensions of the features which, in your case of 2D input, is X.shape[-1]

Convolution neural network usage

I have regression problem, where there are around 20 features, the expected output is prices(in float).
Can I use Convolutional neural network here to predict the prices. I used both 1D,2D convolution.
But I get below errors,
For 2D,error is
ValueError: Input 0 of layer sequential_4 is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 18)
For 1D, error is
ValueError: Input 0 of layer sequential_4 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (None, 18)
Can I use CNN for data other than images? What I am missing here. Please help here.
Below is the code,
model2 = tf.keras.Sequential()
model2.add(tf.keras.layers.Conv1D(32,kernel_size=(3),strides=1, activation='relu'))
model2.add(tf.keras.layers.BatchNormalization())
model2.add(tf.keras.layers.Conv1D(64, kernel_size=(3), strides=(2)))
model2.add(tf.keras.layers.ReLU())
model2.add(tf.keras.layers.BatchNormalization())
model2.add(tf.keras.layers.Dense(1, activation='linear'))
model2.compile(optimizer='adam',loss='mean_absolute_error',metrics['mean_absolute_error'])
I found the issue. There was issue in model.fit. Instead of calling model.fit(X_train,y_train,val=(X_test,y_test)). I had called in this way model.fit((X_train,y_train), val=(X_test,y_Test)). Model was trying to call it as fit_generator instead of fit because of the extra bracket.

np array shape for conv1d input

I have a model with conv1d as the first layer.
My data is time series data where each sample consists of 41 time steps where each time step has 4 features.
I have about 1000 samples.
I have specified the input shape of the conve1d layer to be (41,4) as it supposed to be.
However, I keep getting the following error: Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2.
I suspect that the problem is that the shape of X is (1000,) while the shape of X[0] is (41,4). Has anyone encountered this problem?
Thanks.
l1=Input(shape=(41,4))
x=Conv1D(64,(4))(l1)
x=GlobalMaxPooling1D()(x)
x=Dense(1)(x)
model=Model(l1,x)
model.compile('rmsprop','binary_crossentropy',metrics=['acc'])
model.fit(X,y,32,10)
You defined an expected input on your Conv1D to be be 2D -> (41, 4)
But you give to it an input of shape (41,), be consistant in your definitions !
If you specify the input_shape in your Conv1D layer, you don't need to feed an Input layer to it.
Or you can change the shape of this Input layer to be consistant with this input_shape.

How to expand output of embedding layer in keras

I have the following network:
model = Sequential()
model.add(Embedding(400000, 100, weights=[emb], input_length=12, trainable=False))
model.add(Conv2D(256,(2,2),activation='relu'))
the output from the embedding layer is of shape (batchSize, 12, 100). The conv2D layer requires an input of shape (batchSize, filter, 12, 100), and I get the following error:
Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=3
So, how can I expand the output from the embedding layer to make it proper for the Conv2D layer?
I'm using Keras with Tensorflow as the back end.
Adding a reshape Layer should be the way to go https://keras.io/layers/core/#reshape
Depending on the concrete situation Conv1D cold although work.
I managed to add another dimension with the following piece of code:
model = Sequential()
model.add(Embedding(400000, 100, weights=[emb], input_length=12, trainable=False))
model.add(Lambda(lambda x: expand_dims(x, 3)))
model.add(Conv2D(256,(2,2),activation='relu'))