tensorflowmachine-learningkerasshapesincompatibility

Keras incompatible shapes NN


So I have this neural network and I am feeding examples "X" and labels "Y" whose shapes are:

X.shape = (10,10,2)
Y.shape = (10,10,2)

The code for the model looks like:

import tensorflow as tf 
from convert import process
import numpy as np

X, Y, rate = process('songs/song1.wav')

X = np.array(X[:10])
Y = np.array(Y[:10])

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128))
model.add(tf.keras.layers.Dense(128))
model.add(tf.keras.layers.Dense(20))

model.compile(optimizer='adam', loss='categorical_crossentropy')
model.fit(X, Y, epochs=2)

Now for some reason once I run this i get the error:

ValueError: Shapes (None, 10, 2) and (None, 20) are incompatible

I am confused because I fed it data where each example of both "X" and "Y" have shapes (10, 2). So why is it saying that I passed it (None, 10, 2) and (None, 20)


Solution

  • Your last layer uses linear activation whereas you choose categorical_crossentropy loss. Set either

    model.add(tf.keras.layers.Dense(20, activations='softmax'))
    ....loss='categorical_crossentropy')
    

    or,

    model.add(tf.keras.layers.Dense(20))
    ....loss='mse')
    

    Also check your data shape, especially the label (y).